Reorganization

This commit is contained in:
David Doblas Jiménez 2021-09-20 18:02:00 +02:00
parent 7c8165d9c2
commit 2a1db7eda3
50 changed files with 0 additions and 2264 deletions

View File

@ -1,30 +0,0 @@
#!/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()}")

View File

@ -1,41 +0,0 @@
#!/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()}")

View File

@ -1,34 +0,0 @@
#!/usr/bin/env python3
"""
Created on 18 Mar 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 3 of Project Euler
https://projecteuler.net/problem=3
"""
from utils import timeit
@timeit("Problem 3")
def compute():
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
ans = 600851475143
factor = 2
while factor * factor < ans:
while ans % factor == 0:
ans = ans // factor
factor += 1
return ans
if __name__ == "__main__":
print(f"Result for problem 3: {compute()}")

View File

@ -1,36 +0,0 @@
#!/usr/bin/env python3
"""
Created on 18 Mar 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 4 of Project Euler
https://projecteuler.net/problem=4
"""
from utils import timeit
@timeit("Problem 4")
def compute():
"""
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
ans = 0
for i in range(100, 1000):
for j in range(100, 1000):
palindrome = i * j
s = str(palindrome)
if s == s[::-1] and palindrome > ans:
ans = palindrome
return ans
if __name__ == "__main__":
print(f"Result for problem 4: {compute()}")

View File

@ -1,41 +0,0 @@
#!/usr/bin/env python3
"""
Created on 23 Apr 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 5 of Project Euler
https://projecteuler.net/problem=5
"""
import math
from utils import timeit
# The LCM of two natural numbers x and y is given by:
# def lcm(x, y):
# return x * y // math.gcd(x, y)
# It is possible to compute the LCM of more than two numbers by iteratively
# computing the LCM of two numbers, i.e. LCM(a, b, c) = LCM(a, LCM(b, c))
@timeit("Problem 5")
def compute():
"""
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?
"""
ans = 1
for i in range(1, 21):
ans *= i // math.gcd(i, ans)
return ans
if __name__ == "__main__":
print(f"Result for problem 5: {compute()}")

View File

@ -1,39 +0,0 @@
#!/usr/bin/env python3
"""
Created on 17 Jun 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 6 of Project Euler
https://projecteuler.net/problem=6
"""
from utils import timeit
@timeit("Problem 6")
def compute():
"""
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. Statement
"""
n = 100
square_of_sum = sum(i for i in range(1, n+1))**2
sum_squares = sum(i**2 for i in range(1, n+1))
diff = square_of_sum - sum_squares
return diff
if __name__ == "__main__":
print(f"Result for Problem 6: {compute()}")

View File

@ -1,34 +0,0 @@
#!/usr/bin/env python3
"""
Created on 28 Jun 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 7 of Project Euler
https://projecteuler.net/problem=7
"""
from utils import timeit, is_prime
@timeit("Problem 7")
def compute():
"""
# Statement
"""
number = 2
primeList = []
while len(primeList) < 10001:
if is_prime(number):
primeList.append(number)
number += 1
ans = primeList[len(primeList)-1]
return ans
if __name__ == "__main__":
print(f"Result for Problem 7: {compute()}")

View File

@ -1,67 +0,0 @@
#!/usr/bin/env python3
"""
Created on 28 Abr 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 8 of Project Euler
https://projecteuler.net/problem=8
"""
from utils import timeit
@timeit("Problem 8")
def compute():
"""
The four adjacent digits in the 1000-digit number that have the
greatest product are 9 × 9 × 8 × 9 = 5832.
731671...963450
Find the thirteen adjacent digits in the 1000-digit number that have
the greatest product. What is the value of this product?
"""
NUM = """
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
"""
num = NUM.replace('\n', '').replace(' ', '')
adjacent_digits = 13
target = len(num) - adjacent_digits #- 1
ans, i = 0, 0
while i < target:
a, j = 1, i
while j < (i + adjacent_digits):
a = a * int(num[j])
j += 1
if a > ans:
ans = a
i += 1
return ans
if __name__ == "__main__":
print(f"Result for Problem 8: {compute()}")

View File

@ -1,38 +0,0 @@
#!/usr/bin/env python3
"""
Created on 26 Aug 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 9 of Project Euler
https://projecteuler.net/problem=9
"""
from utils import timeit
@timeit("Problem 9")
def compute():
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c,
for which a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
upper_limit = 1000
for a in range(1, upper_limit + 1):
for b in range(a + 1, upper_limit + 1):
c = upper_limit - a - b
if a * a + b * b == c * c:
# It is now implied that b < c, because we have a > 0
return a * b * c
if __name__ == "__main__":
print(f"Result for Problem 9: {compute()}")

View File

@ -1,30 +0,0 @@
#!/usr/bin/env python3
"""
Created on 26 Aug 2017
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 10 of Project Euler
https://projecteuler.net/problem=10
"""
import math
from utils import timeit, list_primes
@timeit("Problem 10")
def compute():
"""
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
ans = sum(list_primes(1_999_999))
return ans
if __name__ == "__main__":
print(f"Result for Problem 10: {compute()}")

View File

@ -1,75 +0,0 @@
#!/usr/bin/env python3
"""
Created on 07 Jul 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 11 of Project Euler
https://projecteuler.net/problem=11
"""
from utils import timeit
GRID = [
[ 8, 2,22,97,38,15, 0,40, 0,75, 4, 5, 7,78,52,12,50,77,91, 8],
[49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48, 4,56,62, 0],
[81,49,31,73,55,79,14,29,93,71,40,67,53,88,30, 3,49,13,36,65],
[52,70,95,23, 4,60,11,42,69,24,68,56, 1,32,56,71,37, 2,36,91],
[22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80],
[24,47,32,60,99, 3,45, 2,44,75,33,53,78,36,84,20,35,17,12,50],
[32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70],
[67,26,20,68, 2,62,12,20,95,63,94,39,63, 8,40,91,66,49,94,21],
[24,55,58, 5,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72],
[21,36,23, 9,75, 0,76,44,20,45,35,14, 0,61,33,97,34,31,33,95],
[78,17,53,28,22,75,31,67,15,94, 3,80, 4,62,16,14, 9,53,56,92],
[16,39, 5,42,96,35,31,47,55,58,88,24, 0,17,54,24,36,29,85,57],
[86,56, 0,48,35,71,89, 7, 5,44,44,37,44,60,21,58,51,54,17,58],
[19,80,81,68, 5,94,47,69,28,73,92,13,86,52,17,77, 4,89,55,40],
[ 4,52, 8,83,97,35,99,16, 7,97,57,32,16,26,26,79,33,27,98,66],
[88,36,68,87,57,62,20,72, 3,46,33,67,46,55,12,32,63,93,53,69],
[ 4,42,16,73,38,25,39,11,24,94,72,18, 8,46,29,32,40,62,76,36],
[20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74, 4,36,16],
[20,73,35,29,78,31,90, 1,74,31,49,71,48,86,81,16,23,57, 5,54],
[ 1,70,54,71,83,51,54,69,16,92,33,48,61,43,52, 1,89,19,67,48]
]
def grid_product(x, y, dx, dy, n):
result = 1
for i in range(n):
result *= GRID[y + i * dy][x + i * dx]
return result
@timeit("Problem 11")
def compute():
"""
In the 20x20 grid above, four numbers along a diagonal line have been
marked in red.
The product of these numbers is 26 x 63 x 78 x 14 = 1788696.
What is the greatest product of four adjacent numbers in any direction
(up, down, left, right, or diagonally) in the 20x20 grid?
"""
ans = 0
width = height = len(GRID)
adjacent_nums = 4
for y in range(height):
for x in range(width):
if x + adjacent_nums <= width:
ans = max(grid_product(x, y, 1, 0, adjacent_nums), ans)
if y + adjacent_nums <= height:
ans = max(grid_product(x, y, 0, 1, adjacent_nums), ans)
if x + adjacent_nums <= width and y + adjacent_nums <= height:
ans = max(grid_product(x, y, 1, 1, adjacent_nums), ans)
if x - adjacent_nums >= -1 and y + adjacent_nums <= height:
ans = max(grid_product(x, y, -1, 1, adjacent_nums), ans)
return ans
if __name__ == "__main__":
print(f"Result for Problem 11: {compute()}")

View File

@ -1,67 +0,0 @@
#!/usr/bin/env python3
"""
Created on 01 Jan 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 12 of Project Euler
https://projecteuler.net/problem=12
"""
import itertools
from utils import timeit
from math import sqrt, floor
# Returns the number of integers in the range [1, n] that divide n.
def num_divisors(n):
end = floor(sqrt(n))
divs = []
for i in range(1, end + 1):
if n % i == 0:
divs.append(i)
if end**2 == n:
divs.pop()
return 2*len(divs)
@timeit("Problem 12")
def compute():
"""
The sequence of triangle numbers is generated by adding the natural
numbers. So the 7th triangle number would be:
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred
divisors?
"""
triangle = 0
for i in itertools.count(1):
# This is the ith triangle number, i.e. num = 1 + 2 + ... + i =
# = i*(i+1)/2
triangle += i
if num_divisors(triangle) > 500:
return str(triangle)
if __name__ == "__main__":
print(f"Result for Problem 12: {compute()}")

View File

@ -1,32 +0,0 @@
#!/usr/bin/env python3
"""
Created on 1 Jan 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 13 of Project Euler
https://projecteuler.net/problem=13
"""
from utils import timeit
@timeit("Problem 13")
def compute():
"""
Work out the first ten digits of the sum of the following one-hundred
50-digit numbers.
"""
with open("../files/Problem13.txt", "r") as f:
num = f.readlines()
result = 0
for line in num:
result += int(line)
return str(result)[:10]
if __name__ == "__main__":
print(f"Result for Problem 13: {compute()}")

View File

@ -1,63 +0,0 @@
#!/usr/bin/env python3
"""
Created on 7 Jan 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 14 of Project Euler
https://projecteuler.net/problem=14
"""
from utils import timeit
def chain_length(n, terms):
length = 0
while n != 1:
if n in terms:
length += terms[n]
break
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
length += 1
return length
@timeit("Problem 14")
def compute():
"""
The following iterative sequence is defined for the set of positive
integers:
n n/2 (n is even)
n 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following
sequence:
13 40 20 10 5 16 8 4 2 1
It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms. Although it has not been proved yet (Collatz Problem),
it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
"""
ans = 0
limit = 1_000_000
score = 0
terms = dict()
for i in range(1, limit):
terms[i] = chain_length(i, terms)
if terms[i] > score:
score = terms[i]
ans = i
return ans
if __name__ == "__main__":
print(f"Result for Problem 14: {compute()}")

View File

@ -1,31 +0,0 @@
#!/usr/bin/env python3
"""
Created on 7 Jan 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 15 of Project Euler
https://projecteuler.net/problem=15
"""
from math import factorial
from utils import timeit
@timeit("Problem 15")
def compute():
"""
Starting in the top left corner of a 2×2 grid, and only being able to
move to the right and down, there are exactly 6 routes to the bottom
right corner.
How many such routes are there through a 20×20 grid?
"""
n = 20
return int(factorial(2*n) / (factorial(n) * factorial(2*n - n)))
if __name__ == "__main__":
print(f"Result for Problem 15: {compute()}")

View File

@ -1,28 +0,0 @@
#!/usr/bin/env python3
"""
Created on 13 Jan 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 16 of Project Euler
https://projecteuler.net/problem=16
"""
from utils import timeit
@timeit("Problem 16")
def compute():
"""
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
"""
n = 1000
return sum(int(digit) for digit in str(2**n))
if __name__ == "__main__":
print(f"Result for Problem 16: {compute()}")

View File

@ -1,62 +0,0 @@
#!/usr/bin/env python3
"""
Created on 13 Jan 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 17 of Project Euler
https://projecteuler.net/problem=17
"""
from utils import timeit
def num2letters(num):
nums = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',
15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty',
50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty',
90: 'ninety', 100: 'hundred', 1000: 'thousand'}
if num <= 20:
return len(nums[num])
elif num < 100:
tens, units = divmod(num, 10)
return len(nums[tens * 10]) + num2letters(units)
elif num < 1000:
hundreds, rest = divmod(num, 100)
if rest:
return num2letters(hundreds) + len(nums[100]) + len('and') +\
num2letters(rest)
else:
return num2letters(hundreds) + len(nums[100])
else:
thousands, rest = divmod(num, 1000)
return num2letters(thousands) + len(nums[1000])
@timeit("Problem 17")
def compute():
"""
If the numbers 1 to 5 are written out in words: one, two, three, four,
five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written
out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and
forty-two) contains 23 letters and 115 (one hundred and fifteen) contains
20 letters. The use of "and" when writing out numbers is in compliance
with British usage.
"""
n = 1000
letters = 0
for num in range(1, n + 1):
letters += num2letters(num)
return letters
if __name__ == "__main__":
print(f"Result for Problem 17: {compute()}")

View File

@ -1,56 +0,0 @@
#!/usr/bin/env python3
"""
Created on 15 Sep 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 18 of Project Euler
https://projecteuler.net/problem=18
"""
from utils import timeit
triangle = [ # Mutable
[75],
[95,64],
[17,47,82],
[18,35,87,10],
[20, 4,82,47,65],
[19, 1,23,75, 3,34],
[88, 2,77,73, 7,63,67],
[99,65, 4,28, 6,16,70,92],
[41,41,26,56,83,40,80,70,33],
[41,48,72,33,47,32,37,16,94,29],
[53,71,44,65,25,43,91,52,97,51,14],
[70,11,33,28,77,73,17,78,39,68,17,57],
[91,71,52,38,17,14,91,43,58,50,27,29,48],
[63,66, 4,68,89,53,67,30,73,16,69,87,40,31],
[ 4,62,98,27,23, 9,70,98,73,93,38,53,60, 4,23],
]
@timeit("Problem 18")
def compute():
"""
By starting at the top of the triangle below and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle above
"""
for i in reversed(range(len(triangle) - 1)):
for j in range(len(triangle[i])):
triangle[i][j] += max(triangle[i + 1][j], triangle[i + 1][j + 1])
return triangle[0][0]
if __name__ == "__main__":
print(f"Result for Problem 18: {compute()}")

View File

@ -1,44 +0,0 @@
#!/usr/bin/env python3
"""
Created on 15 Sep 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 19 of Project Euler
https://projecteuler.net/problem=19
"""
from datetime import date
from utils import timeit
@timeit("Problem 19")
def compute():
"""
You are given the following information, but you may prefer to do some
research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September, April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century
unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth
century (1 Jan 1901 to 31 Dec 2000)?
"""
sundays = 0
for y in range(1901, 2001):
for m in range (1, 13):
if date(y, m, 1).weekday() == 6:
sundays += 1
return sundays
if __name__ == "__main__":
print(f"Result for Problem 19: {compute()}")

View File

@ -1,35 +0,0 @@
#!/usr/bin/env python3
"""
Created on 15 Sep 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 20 of Project Euler
https://projecteuler.net/problem=20
"""
from math import factorial
from utils import timeit
@timeit("Problem 20")
def compute():
"""
n! means n × (n 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is:
3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
fact = factorial(100)
sum_digits = sum(int(digit) for digit in str(fact))
return sum_digits
if __name__ == "__main__":
print(f"Result for Problem 20: {compute()}")

View File

@ -1,42 +0,0 @@
#!/usr/bin/env python3
"""
Created on 15 Sep 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 21 of Project Euler
https://projecteuler.net/problem=21
"""
from utils import timeit
def sum_divisors(n):
return sum(i for i in range(1, n//2+1) if n%i==0)
@timeit("Problem 21")
def compute():
"""
Let d(n) be defined as the sum of proper divisors of n (numbers
less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an amicable
pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22,
44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are
1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
"""
n = 10000
sum_amicable = 0
for i in range(1, n):
value = sum_divisors(i)
if i != value and sum_divisors(value) == i:
sum_amicable += i
return sum_amicable
if __name__ == "__main__":
print(f"Result for Problem 21: {compute()}")

View File

@ -1,42 +0,0 @@
#!/usr/bin/env python3
"""
Created on 31 Dec 2018
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 22 of Project Euler
https://projecteuler.net/problem=22
"""
from pathlib import Path
from utils import timeit
@timeit("Problem 22")
def compute():
"""
Using names.txt, a 46K text file containing over five-thousand first names,
begin by sorting it into alphabetical order. Then working out the
alphabetical value for each name, multiply this value by its alphabetical
position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which
is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So,
COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
"""
file = Path("/datos/Scripts/Gitea/Project_Euler/src/files/Problem22.txt")
with open(file, 'r') as f:
names = sorted(f.read().replace('"', '').split(','))
result = 0
for idx, name in enumerate(names, 1):
result += sum(ord(c) - 64 for c in name) * idx
return result
if __name__ == "__main__":
print(f"Result for Problem 22: {compute()}")

View File

@ -1,58 +0,0 @@
#!/usr/bin/env python3
"""
Created on 05 Jan 2019
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 23 of Project Euler
https://projecteuler.net/problem=23
"""
from utils import timeit
@timeit("Problem 23")
def compute():
"""
A perfect number is a number for which the sum of its proper divisors is
exactly equal to the number. For example, the sum of the proper divisors
of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect
number.
A number n is called deficient if the sum of its proper divisors is less
than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
number that can be written as the sum of two abundant numbers is 24. By
mathematical analysis, it can be shown that all integers greater than 28123
can be written as the sum of two abundant numbers. However, this upper
limit cannot be reduced any further by analysis even though it is known
that the greatest number that cannot be expressed as the sum of two
abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the
sum of two abundant numbers.
"""
LIMIT = 28124
divisorsum = [0] * LIMIT
for i in range(1, LIMIT):
for j in range(i * 2, LIMIT, i):
divisorsum[j] += i
abundantnums = [i for (i, x) in enumerate(divisorsum) if x > i]
expressible = [False] * LIMIT
for i in abundantnums:
for j in abundantnums:
if i + j < LIMIT:
expressible[i + j] = True
else:
break
ans = sum(i for (i, x) in enumerate(expressible) if not x)
return ans
if __name__ == "__main__":
print(f"Result for Problem 23: {compute()}")

View File

@ -1,37 +0,0 @@
#!/usr/bin/env python3
"""
Created on 11 Sep 2019
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 24 of Project Euler
https://projecteuler.net/problem=24
"""
from itertools import permutations
from utils import timeit
@timeit("Problem 24")
def compute():
"""
A permutation is an ordered arrangement of objects. For example, 3124 is
one possible permutation of the digits 1, 2, 3 and 4. If all of the
permutations are listed numerically or alphabetically, we call it
lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits
0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
"""
digits = list(range(10))
_permutations = list(permutations(digits))
print(_permutations[0])
return "".join(str(digit) for digit in _permutations[999999])
if __name__ == "__main__":
print(f"Result for Problem 24: {compute()}")

View File

@ -1,54 +0,0 @@
#!/usr/bin/env python3
"""
Created on 11 Sep 2019
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 25 of Project Euler
https://projecteuler.net/problem=25
"""
from utils import timeit
@timeit("Problem 25")
def compute():
"""
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to
contain 1000 digits?
"""
a, b = 1, 1
index = 2
while len(str(b)) < 1000:
a, b = b, b+a
index += 1
return index
if __name__ == "__main__":
print(f"Result for Problem 25: {compute()}")

View File

@ -1,52 +0,0 @@
#!/usr/bin/env python3
"""
Created on 11 Sep 2019
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 26 of Project Euler
https://projecteuler.net/problem=26
"""
from utils import timeit
@timeit("Problem 26")
def compute():
"""
A unit fraction contains 1 in the numerator. The decimal representation
of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle.
It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring
cycle in its decimal fraction part.
"""
cycle_length = 0
number_d = 0
for number in range(3, 1000, 2):
if number % 5 == 0:
continue
p = 1
while 10**p % number != 1:
p += 1
if p > cycle_length:
cycle_length, number_d = p, number
return number_d
if __name__ == "__main__":
print(f"Result for Problem 26: {compute()}")

View File

@ -1,58 +0,0 @@
#!/usr/bin/env python3
"""
Created on 15 Sep 2019
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 27 of Project Euler
https://projecteuler.net/problem=27
"""
from utils import timeit, is_prime
@timeit("Problem 27")
def compute():
"""
Euler discovered the remarkable quadratic formula:
n^2 + n + 41
It turns out that the formula will produce 40 primes for the consecutive
integer values 0n39. However, when n=40, 40^2+40+41=40(40+1)+41 is
divisible by 41, and certainly when n=41,41^2+41+41 is clearly divisible
by 41.
The incredible formula n^279n+1601 was discovered, which produces 80
primes for the consecutive values 0n79. The product of the coefficients,
79 and 1601, is 126479.
Considering quadratics of the form:
n^2 + an + b
where |a|<1000, |b|1000 and |n| is the modulus/absolute value of n
e.g. |11|=11 and |4|=4
Find the product of the coefficients, a and b, for the quadratic expression
that produces the maximum number of primes for consecutive values of n,
starting with n=0.
"""
LIMIT = 1000
consecutive_values = 0
for a in range(-999, LIMIT):
for b in range(LIMIT + 1):
n = 0
while is_prime(abs((n ** 2) + (a * n) + b)):
n += 1
if n > consecutive_values:
consecutive_values = n
c = a * b
return c
if __name__ == "__main__":
print(f"Result for Problem 27: {compute()}")

View File

@ -1,48 +0,0 @@
#!/usr/bin/env python3
"""
Created on 3 Jan 2020
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 28 of Project Euler
https://projecteuler.net/problem=28
"""
from utils import timeit
@timeit("Problem 28")
def compute():
"""
Starting with the number 1 and moving to the right in a clockwise
direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral
formed in the same way?
"""
size = 1001 # Must be odd
ans = 1 # Special case for size 1
step = 0
i, cur = 1, 1
while step < size-1:
step = i * 2
for j in range(1, 5):
cur += step
ans += cur
i += 1
return ans
if __name__ == "__main__":
print(f"Result for Problem 28: {compute()}")

View File

@ -1,38 +0,0 @@
#!/usr/bin/env python3
"""
Created on 3 Jan 2020
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 29 of Project Euler
https://projecteuler.net/problem=29
"""
from utils import timeit
@timeit("Problem 29")
def compute():
"""
Consider all integer combinations of ab for 2 a 5 and 2 b 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we
get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2a100
and 2b100?
"""
terms = set(a**b for a in range(2, 101) for b in range(2, 101))
return len(terms)
if __name__ == "__main__":
print(f"Result for Problem 29: {compute()}")

View File

@ -1,42 +0,0 @@
#!/usr/bin/env python3
"""
Created on 3 Jan 2020
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 30 of Project Euler
https://projecteuler.net/problem=30
"""
from utils import timeit
@timeit("Problem 30")
def compute():
"""
Surprisingly there are only three numbers that can be written as the sum
of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth
powers of their digits.
"""
def power_digit_sum(pow, n):
return sum(int(c)**pow for c in str(n))
ans = sum(i for i in range(2, 1000000) if i == power_digit_sum(5, i))
return ans
if __name__ == "__main__":
print(f"Result for Problem 30: {compute()}")

View File

@ -1,43 +0,0 @@
#!/usr/bin/env python3
"""
Created on 24 Feb 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 31 of Project Euler
https://projecteuler.net/problem=31
"""
from itertools import product
from utils import timeit
@timeit("Problem 31")
def compute():
"""
In the United Kingdom the currency is made up of pound (£) and pence (p).
There are eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
"""
no_ways = 0
coins = [2, 5, 10, 20, 50, 100]
bunch_of_coins = product(*[range(0, 201, i) for i in coins])
for money in bunch_of_coins:
if sum(money) <= 200:
no_ways += 1
# consider also the case for 200 coins of 1p
return no_ways + 1
if __name__ == "__main__":
print(f"Result for Problem 31: {compute()}")

View File

@ -1,45 +0,0 @@
#!/usr/bin/env python3
"""
Created on 26 Feb 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 32 of Project Euler
https://projecteuler.net/problem=32
"""
from utils import timeit
@timeit("Problem 32")
def compute():
"""
We shall say that an n-digit number is pandigital if it makes use of all
the digits 1 to n exactly once; for example, the 5-digit number, 15234, is
1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing
multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity
can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only
include it once in your sum.
"""
ans = set()
pandigital = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
for x in range(1, 100):
for y in range(100, 10000):
# product = x * y
if sorted(str(x) + str(y) + str(x * y)) == pandigital:
ans.add(x * y)
return sum(ans)
if __name__ == "__main__":
print(f"Result for Problem 32: {compute()}")

View File

@ -1,47 +0,0 @@
#!/usr/bin/env python3
"""
Created on 04 Mar 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 33 of Project Euler
https://projecteuler.net/problem=33
"""
from utils import timeit
@timeit("Problem 33")
def compute():
"""
The fraction 49/98 is a curious fraction, as an inexperienced mathematician
in attempting to simplify it may incorrectly believe that 49/98 = 4/8,
which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly four non-trivial examples of this type of fraction, less
than one in value, and containing two digits in the numerator and denominator.
If the product of these four fractions is given in its lowest common terms,
find the value of the denominator.
"""
numerator = 1
denominator = 1
for x in range(10, 100):
for y in range(10, 100):
if x < y:
if str(x)[1] == str(y)[0]:
if int(str(y)[1]) != 0:
if int(str(x)[0]) / int(str(y)[1]) == x / y:
numerator *= x
denominator *= y
return int(denominator/numerator)
if __name__ == "__main__":
print(f"Result for Problem 33: {compute()}")

View File

@ -1,41 +0,0 @@
#!/usr/bin/env python3
"""
Created on 02 Apr 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 34 of Project Euler
https://projecteuler.net/problem=34
"""
import math
from utils import timeit
@timeit("Problem 34")
def compute():
"""
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial
of their digits.
Note: As 1! = 1 and 2! = 2 are not sums they are not included.
"""
ans = 0
for num in range(10,2540160):
sum_of_factorial = 0
for digit in str(num):
sum_of_factorial += math.factorial(int(digit))
if sum_of_factorial == num:
ans += sum_of_factorial
return ans
if __name__ == "__main__":
print(f"Result for Problem 34: {compute()}")

View File

@ -1,48 +0,0 @@
#!/usr/bin/env python3
"""
Created on 02 Apr 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 35 of Project Euler
https://projecteuler.net/problem=35
"""
from utils import timeit, is_prime
def circular_number(n):
n = str(n)
result = []
for i in range(len(n)):
result.append(int(n[i:] + n[:i]))
return result
@timeit("Problem 35")
def compute():
"""
The number, 197, is called a circular prime because all rotations of the
digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100:
2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
"""
circular_primes = []
for i in range(2, 1_000_000):
if is_prime(i):
all_primes = True
for j in circular_number(i):
if not is_prime(j):
all_primes = False
break
if all_primes:
circular_primes.append(i)
return len(circular_primes)
if __name__ == "__main__":
print(f"Result for Problem 35: {compute()}")

View File

@ -1,35 +0,0 @@
#!/usr/bin/env python3
"""
Created on 08 Apr 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 36 of Project Euler
https://projecteuler.net/problem=36
"""
from utils import timeit
def is_palidrome(num):
return str(num) == str(num)[::-1]
@timeit("Problem 36")
def compute():
"""
The decimal number, 585 = 1001001001_2 (binary), is palindromic
in both bases.
Find the sum of all numbers, less than one million, which are palindromic
in base 10 and base 2.
"""
ans = 0
for i in range(1, 1_000_001, 2):
if is_palidrome(i) and is_palidrome(bin(i)[2:]):
ans += i
return ans
if __name__ == "__main__":
print(f"Result for Problem 36: {compute()}")

View File

@ -1,46 +0,0 @@
#!/usr/bin/env python3
"""
Created on 09 Apr 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 37 of Project Euler
https://projecteuler.net/problem=37
"""
from utils import timeit, list_primes, is_prime
def is_truncatable_prime(number):
num_str = str(number)
for i in range(1, len(num_str)):
if not is_prime(int(num_str[i:])) or not is_prime(int(num_str[:-i])):
return False
return True
@timeit("Problem 37")
def compute():
"""
The number 3797 has an interesting property. Being prime itself, it is
possible to continuously remove digits from left to right, and remain
prime at each stage: 3797, 797, 97, and 7.
Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left
to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
"""
ans = 0
primes = list_primes(1_000_000)
# Statement of the problem says this
for number in primes[4:]:
if is_truncatable_prime(number):
ans += number
return ans
if __name__ == "__main__":
print(f"Result for Problem 37: {compute()}")

View File

@ -1,56 +0,0 @@
#!/usr/bin/env python3
"""
Created on 03 Jun 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 38 of Project Euler
https://projecteuler.net/problem=38
"""
from utils import timeit
@timeit("Problem 38")
def compute():
"""
Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital,
192384576. We will call 192384576 the concatenated product of
192 and (1,2,3)
The same can be achieved by starting with 9 and multiplying by
1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is
the concatenated product of 9 and (1,2,3,4,5).
What is the largest 1 to 9 pandigital 9-digit number that can
be formed as the concatenated product of an integer with
(1,2, ... , n) where n > 1?
"""
results = []
# Number must 4 digits (exactly) to be pandigital
# if n > 1
for i in range(1, 10_000):
integer = 1
number = ""
while len(number) < 9:
number += str(integer * i)
if sorted(number) == list('123456789'):
results.append(number)
integer += 1
return max(results)
if __name__ == "__main__":
print(f"Result for Problem 38: {compute()}")

View File

@ -1,44 +0,0 @@
#!/usr/bin/env python3
"""
Created on 05 Jun 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 39 of Project Euler
https://projecteuler.net/problem=39
"""
from utils import timeit
@timeit("Problem 39")
def compute():
"""
If p is the perimeter of a right angle triangle with integral length sides,
{a,b,c}, there are exactly three solutions for p = 120:
{20,48,52}, {24,45,51}, {30,40,50}
For which value of p 1000, is the number of solutions maximised?
"""
ans, val = 0, 0
for p in range(2, 1001, 2):
sol = 0
for a in range(1, p):
for b in range(a+1, p-2*a):
c = p - (a + b)
if a**2 + b**2 == c**2:
sol += 1
elif a**2 + b**2 > c**2:
# As we continue our innermost loop, the left side
# gets bigger, right gets smaller, so we're done here
break
if sol > ans:
ans, val = sol, p
return val
if __name__ == "__main__":
print(f"Result for Problem 39: {compute()}")

View File

@ -1,43 +0,0 @@
#!/usr/bin/env python3
"""
Created on 23 Jun 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 40 of Project Euler
https://projecteuler.net/problem=40
"""
from utils import timeit
@timeit("Problem 40")
def compute():
"""
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If d_n represents the n^th digit of the fractional part, find the value of the following expression.
d_1 × d_{10} × d_{100} × d_{1_000} × d_{10_000} × d_{100_000} × d_{1_000_000}
"""
fraction = ''
for i in range(1, 1_000_000):
fraction += str(i)
ans = 1
for i in range(7):
ans*= int(fraction[10**i - 1])
return ans
if __name__ == "__main__":
print(f"Result for Problem 40: {compute()}")

View File

@ -1,39 +0,0 @@
#!/usr/bin/env python3
"""
Created on 29 Jun 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 41 of Project Euler
https://projecteuler.net/problem=41
"""
from utils import timeit, is_prime
@timeit("Problem 41")
def compute():
"""
We shall say that an n-digit number is pandigital if it makes
use of all the digits 1 to n exactly once. For example, 2143 is
a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
def is_pandigital(number):
number = sorted(str(number))
check = [str(i) for i in range(1, len(number)+1)]
if number == check:
return True
return False
for ans in range(7654321, 1, -1):
if is_pandigital(ans):
if is_prime(ans):
return ans
if __name__ == "__main__":
print(f"Result for Problem 41: {compute()}")

View File

@ -1,50 +0,0 @@
#!/usr/bin/env python3
"""
Created on 26 Jul 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 42 of Project Euler
https://projecteuler.net/problem=42
"""
from utils import timeit
@timeit("Problem 42")
def compute():
"""
The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1);
so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical
position and adding these values we form a word value. For example, the word value
for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we
shall call the word a triangle word.
Using words.txt, a 16K text file containing nearly two-thousand common English words,
how many are triangle words?
"""
def triangle_number(num):
return int(0.5*num*(num+1))
def word_to_value(word):
return sum(ord(letter)-64 for letter in word)
triangular_numbers = [triangle_number(n) for n in range(27)]
ans = 0
with open("files/Problem42.txt", "r") as f:
words = f.readline().strip('"').split('","')
for word in words:
if word_to_value(word) in triangular_numbers:
ans += 1
return ans
if __name__ == "__main__":
print(f"Result for Problem 42: {compute()}")

View File

@ -1,55 +0,0 @@
#!/usr/bin/env python3
"""
Created on 03 Aug 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 43 of Project Euler
https://projecteuler.net/problem=43
"""
from itertools import permutations
from utils import timeit
@timeit("Problem 43")
def compute():
"""
The number, 1406357289, is a 0 to 9 pandigital number because
it is made up of each of the digits 0 to 9 in some order, but
it also has a rather interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this
way, we note the following:
d2d3d4=406 is divisible by 2
d3d4d5=063 is divisible by 3
d4d5d6=635 is divisible by 5
d5d6d7=357 is divisible by 7
d6d7d8=572 is divisible by 11
d7d8d9=728 is divisible by 13
d8d9d10=289 is divisible by 17
Find the sum of all 0 to 9 pandigital numbers with this property.
"""
ans = []
pandigital = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for n in permutations(pandigital):
n_ = "".join(n)
if n_[0] != "0" and sorted("".join(n_)) == pandigital:
if int(n_[7:]) % 17 == 0:
if int(n_[6:9]) % 13 == 0:
if int(n_[5:8]) % 11 == 0:
if int(n_[4:7]) % 7 == 0:
if int(n_[3:6]) % 5 == 0:
if int(n_[2:5]) % 3 == 0:
if int(n_[1:4]) % 2 == 0:
ans.append(int(n_))
return sum(ans)
if __name__ == "__main__":
print(f"Result for Problem 43: {compute()}")

View File

@ -1,48 +0,0 @@
#!/usr/bin/env python3
"""
Created on 30 Aug 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 44 of Project Euler
https://projecteuler.net/problem=44
"""
from itertools import combinations
from operator import add, sub
from utils import timeit
def pentagonal(n):
return int(n*(3*n-1)/2)
@timeit("Problem 44")
def compute():
"""
Pentagonal numbers are generated by the formula, Pn=n(3n1)/2.
The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their
difference, 70 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their
sum and difference are pentagonal and D = |Pk Pj| is minimised.
What is the value of D?
"""
dif = 0
pentagonal_list = set(pentagonal(n) for n in range(1,2500))
pairs = combinations(pentagonal_list, 2)
for p in pairs:
if add(*p) in pentagonal_list and abs(sub(*p)) in pentagonal_list:
dif = (abs(sub(*p)))
# the first one found would be the smallest
break
return dif
if __name__ == "__main__":
print(f"Result for Problem 44: {compute()}")

View File

@ -1,42 +0,0 @@
#!/usr/bin/env python3
"""
Created on 09 Sep 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 45 of Project Euler
https://projecteuler.net/problem=45
"""
from utils import timeit
def pentagonal(n):
return int(n*(3*n-1)/2)
def hexagonal(n):
return int(n*(2*n-1))
@timeit("Problem 45")
def compute():
"""
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
"""
pentagonal_list = set(pentagonal(n) for n in range(2,100_000))
# all hexagonal numbers are also triangle numbers!
hexagonal_list = set(hexagonal(n) for n in range(2,100_000))
ans = sorted(hexagonal_list & pentagonal_list)
# First one is already known
return ans[1]
if __name__ == "__main__":
print(f"Result for Problem 45: {compute()}")

View File

@ -1,48 +0,0 @@
#!/usr/bin/env python3
"""
Created on 12 Sep 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 46 of Project Euler
https://projecteuler.net/problem=46
"""
from utils import timeit, is_prime
def is_goldbach(number):
for i in range(number - 1, 1, -1):
if is_prime(i) and ((number - i) / 2)**0.5 % 1 == 0:
return True
return False
@timeit("Problem 46")
def compute():
"""
It was proposed by Christian Goldbach that every odd composite number
can be written as the sum of a prime and twice a square.
9 = 7 + 2×1^2
15 = 7 + 2×2^2
21 = 3 + 2×3^2
25 = 7 + 2×3^2
27 = 19 + 2×2^2
33 = 31 + 2×1^2
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum
of a prime and twice a square?
"""
ans = 9
while True:
ans += 2
if not is_prime(ans) and not is_goldbach(ans):
return ans
if __name__ == "__main__":
print(f"Result for Problem 46: {compute()}")

View File

@ -1,60 +0,0 @@
#!/usr/bin/env python3
"""
Created on 12 Sep 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 47 of Project Euler
https://projecteuler.net/problem=47
"""
from utils import timeit
def factor(n):
ans = []
d = 2
while d * d <= n:
if n % d == 0:
ans.append(d)
n //= d
else:
d += 1
if n > 1:
ans.append(n)
return ans
@timeit("Problem 47")
def compute():
"""
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 × 7
15 = 3 × 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.
Find the first four consecutive integers to have four distinct prime factors each.
What is the first of these numbers?
"""
ans = []
for number in range(1, 1_000_000):
if len(ans) == 4:
break
elif len(set(factor(number))) == 4:
ans.append(number)
else:
ans = []
return ans[0]
if __name__ == "__main__":
print(f"Result for Problem 47: {compute()}")

View File

@ -1,28 +0,0 @@
#!/usr/bin/env python3
"""
Created on 12 Sep 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 48 of Project Euler
https://projecteuler.net/problem=48
"""
from utils import timeit
@timeit("Problem 48")
def compute():
"""
The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
"""
series = sum(i**i for i in range(1,1001))
return str(series)[-10:]
if __name__ == "__main__":
print(f"Result for Problem 48: {compute()}")

View File

@ -1,41 +0,0 @@
#!/usr/bin/env python3
"""
Created on 18 Sep 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 49 of Project Euler
https://projecteuler.net/problem=49
"""
from utils import timeit, list_primes
@timeit("Problem 49")
def compute():
"""
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms
increases by 3330, is unusual in two ways:
(i) each of the three terms are prime, and,
(ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes,
exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
"""
ans = []
primes_list = sorted(set(list_primes(10_000)) - set(list_primes(1_000)))
for number in primes_list:
if set(list(str(number))) == set(list(str(number+3330))) == set(list(str(number+6660))):
if number+3330 in primes_list and number+6660 in primes_list:
ans.append(str(number)+str(number+3300)+str(number+6660))
# return the second one
return ans[1]
if __name__ == "__main__":
print(f"Result for Problem 49: {compute()}")

View File

@ -1,51 +0,0 @@
#!/usr/bin/env python3
"""
Created on 18 Sep 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for problem 50 of Project Euler
https://projecteuler.net/problem=50
"""
from utils import timeit, list_primes, is_prime
@timeit("Problem 50")
def compute():
"""
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime,
contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
"""
ans = 0
result = 0
prime_list = list_primes(1_000_000)
for i in range(len(prime_list)):
sum = 0
count = 0
for j in prime_list[i:]:
sum += j
count += 1
if is_prime(sum) and count > result:
result = count
ans = sum
# print(sum, result)
if sum > 1_000_000:
break
return ans
if __name__ == "__main__":
print(f"Result for Problem 50: {compute()}")