Solution for problems 1,2

This commit is contained in:
David Doblas Jiménez 2021-06-04 08:10:55 +02:00
parent d221250059
commit fc6cebe8b7
2 changed files with 71 additions and 0 deletions

30
src/Python/Problem001.py Normal file
View File

@ -0,0 +1,30 @@
#!/usr/bin/python3
"""
Created on 14 Mar 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 1 of Project Euler
https://projecteuler.net/problem=1
"""
from utils import timeit
@timeit("Problem 1")
def compute():
"""
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.
"""
ans = sum(x for x in range(1000) if (x % 3 == 0 or x % 5 == 0))
return ans
if __name__ == "__main__":
print(f"Result for problem 1: {compute()}")

41
src/Python/Problem002.py Normal file
View File

@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""
Created on 14 Mar 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 2 of Project Euler
https://projecteuler.net/problem=2
"""
from utils import timeit
@timeit("Problem 2")
def compute():
"""
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, ...
Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
"""
ans = 0
limit = 4_000_000
x, y = 1, 1
z = x + y # Because every third Fibonacci number is even
while z <= limit:
ans += z
x = y + z
y = z + x
z = x + y
return ans
if __name__ == "__main__":
print(f"Result for problem 2: {compute()}")