A few project euler problems.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
sum([x for x in [0..1000] if x % 3 == 0 || x % 5 == 0])
// 233168
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
let fib = fn (n) => ^$fold(fn (ls, i) => [^$ls, ^ls + ^$ls], [1, 1], [0..n])
let fibs = [fib(n) for n in [1..35]]
sum([f for f in fibs if f < 4000000 && f % 2 == 0])
// 4613732
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
let find = fn (f, ls) => if (ls) then (if (f(^ls)) then (^ls) else (find(f, $ls))) else (false)
let factor = fn (n) => find(fn (i) => n % i == 0, [2..n / 2])
600851475143 is larger than int
allows so I'd have to make it support longs to do this one.
It's worth noting that factor
doubles as is_prime
, since it returns false for prime numbers.
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
let gcd = fn (a, b) => if (b == 0) then (a) else (gcd(b, (a % b)))
let lcm = fn (a, b) => (a * b) / (gcd(a, b))
fold(lcm, 1, [1..20])
// 232792560
The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385$$
The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025$$
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
$3025 - 385 = 2640$ . Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
let square = fn (x) => x * x
square(sum([1..100])) - (sum(fmap(square, [1..100])))
Once again the numbers are too big