Background:
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
In this post, I am going to solve the first five problems. I will code the solutions for the remaining problems as time permits. My solutions are also on Github.
Problem one:
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.
Solution:
print(sum([x for x in range(1000) if (x % 3 == 0) or (x % 5 == 0)]))
Problem two:
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.
Solution:
def fibonacci_gen(n):
a, b = 1, 1
while b <= n:
a, b = b, a + b
yield a
def solution(n):
return sum(i for i in fibonacci_gen(n) if not i % 2)
if __name__ == '__main__':
print(solution(4000000))
Problem three:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
Solution:
the_number = 600851475143
prime = 2
while prime * prime < the_number:
while not the_number % prime:
the_number //= prime
prime += 1
print (the_number)
Problem four:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Solution:
i = 100
p = []
while i <= 999:
for j in range(i, 1000):
number = i * j
var = str(number)
if var == var[::-1]:
p.append(int(var))
i += 1
print(max(p))
Problem five:
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?
Solution:
i = 1
for j in (range(1, 21)):
if i % j > 0:
for k in range(1, 21):
if (i * k) % j == 0:
i *= k
break
print(i)
I will add the remaining solutions to this post.