Clean python code

This commit is contained in:
daniele 2023-06-06 19:42:51 +02:00
parent 053b9e572b
commit 26b940a2ac
Signed by: fuxino
GPG Key ID: 981A2B2A3BBF5514
88 changed files with 766 additions and 582 deletions

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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. # 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.
# #
@ -6,6 +6,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -20,9 +21,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 1') print('Project Euler, Problem 1')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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: # 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:
# #
@ -8,6 +8,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -32,9 +33,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 2') print('Project Euler, Problem 2')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,14 +1,14 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The prime factors of 13195 are 5, 7, 13 and 29. # The prime factors of 13195 are 5, 7, 13 and 29.
# #
# What is the largest prime factor of the number 600851475143? # What is the largest prime factor of the number 600851475143?
from math import floor, sqrt
from timeit import default_timer from timeit import default_timer
from projecteuler import is_prime from projecteuler import is_prime
# Recursive approach: if num is prime, return num, otherwise # Recursive approach: if num is prime, return num, otherwise
# recursively look for the largest prime factor of num divided # recursively look for the largest prime factor of num divided
# by its prime factors until only the largest remains. # by its prime factors until only the largest remains.
@ -21,7 +21,6 @@ def max_prime_factor(num):
if num % 2 == 0: if num % 2 == 0:
return max_prime_factor(num // 2) return max_prime_factor(num // 2)
else:
i = 3 i = 3
# If num is divisible by i and i is prime, find largest # If num is divisible by i and i is prime, find largest
@ -30,11 +29,13 @@ def max_prime_factor(num):
if num % i == 0: if num % i == 0:
if is_prime(i): if is_prime(i):
return max_prime_factor(num//i) return max_prime_factor(num//i)
i = i + 2 i = i + 2
# Should never get here # Should never get here
return -1 return -1
def main(): def main():
start = default_timer() start = default_timer()
@ -43,9 +44,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 3') print('Project Euler, Problem 3')
print('Answer: {}'.format(res)) print(f'Answer: {res}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# #
@ -7,6 +7,7 @@
from timeit import default_timer from timeit import default_timer
from projecteuler import is_palindrome from projecteuler import is_palindrome
def main(): def main():
start = default_timer() start = default_timer()
@ -25,9 +26,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 4') print('Project Euler, Problem 4')
print('Answer: {}'.format(max_)) print(f'Answer: {max_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# #
@ -7,6 +7,7 @@
from timeit import default_timer from timeit import default_timer
from projecteuler import lcmm from projecteuler import lcmm
def main(): def main():
start = default_timer() start = default_timer()
@ -19,9 +20,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 5') print('Project Euler, Problem 5')
print('Answer: {}'.format(res)) print(f'Answer: {res}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The sum of the squares of the first ten natural numbers is, # The sum of the squares of the first ten natural numbers is,
# #
@ -14,6 +14,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -30,9 +31,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 6') print('Project Euler, Problem 6')
print('Answer: {}'.format(square_sum - sum_squares)) print(f'Answer: {square_sum - sum_squares}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# #
@ -7,6 +7,7 @@
from timeit import default_timer from timeit import default_timer
from projecteuler import is_prime from projecteuler import is_prime
def main(): def main():
start = default_timer() start = default_timer()
@ -25,9 +26,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 7') print('Project Euler, Problem 7')
print('Answer: {}'.format(n)) print(f'Answer: {n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. # The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
# #
@ -27,6 +27,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -69,9 +70,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 8') print('Project Euler, Problem 8')
print('Answer: {}'.format(max_)) print(f'Answer: {max_}')
print(f'Elapsed time: {end - start:.9f} seconds'.format(end - start))
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# #
@ -11,9 +11,9 @@
# Find the product abc. # Find the product abc.
from math import gcd from math import gcd
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -61,9 +61,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 9') print('Project Euler, Problem 9')
print('Answer: {}'.format(a * b * c)) print(f'Answer: {a * b * c}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# #
@ -7,6 +7,7 @@
from timeit import default_timer from timeit import default_timer
from projecteuler import sieve from projecteuler import sieve
def main(): def main():
start = default_timer() start = default_timer()
@ -25,9 +26,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 10') print('Project Euler, Problem 10')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# In the 20×20 grid below, four numbers along a diagonal line have been marked in red. # In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
# #
@ -29,6 +29,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -51,7 +52,7 @@ def main():
[4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36], [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, 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], [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]]; [1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]]
max_ = 0 max_ = 0
@ -112,9 +113,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 11') print('Project Euler, Problem 11')
print('Answer: {}'.format(max_)) print(f'Answer: {max_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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 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: # The first ten terms would be:
@ -22,6 +22,7 @@
from timeit import default_timer from timeit import default_timer
from projecteuler import count_divisors from projecteuler import count_divisors
def main(): def main():
start = default_timer() start = default_timer()
@ -41,9 +42,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 12') print('Project Euler, Problem 12')
print('Answer: {}'.format(triang)) print(f'Answer: {triang}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. # Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
# #
@ -103,9 +103,9 @@
# 20849603980134001723930671666823555245252804609722 # 20849603980134001723930671666823555245252804609722
# 53503534226472524250874054075591789781264330331690 # 53503534226472524250874054075591789781264330331690
from timeit import default_timer
import numpy as np import numpy as np
from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -219,9 +219,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 13') print('Project Euler, Problem 13')
print('Answer: {}'.format(sum_[:10])) print(f'Answer: {sum_[:10]}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The following iterative sequence is defined for the set of positive integers: # The following iterative sequence is defined for the set of positive integers:
# #
@ -16,13 +16,14 @@
# #
# NOTE: Once the chain starts the terms are allowed to go above one million. # NOTE: Once the chain starts the terms are allowed to go above one million.
from timeit import default_timer
from numpy import zeros from numpy import zeros
from timeit import default_timer
N = 1000000 N = 1000000
collatz_found = zeros(N, dtype=int) collatz_found = zeros(N, dtype=int)
# Recursive function to calculate the Collatz sequence for n. # Recursive function to calculate the Collatz sequence for n.
# If n is even, Collatz(n)=1+Collatz(n/2), if n is odd # If n is even, Collatz(n)=1+Collatz(n/2), if n is odd
# Collatz(n)=1+Collatz(3*n+1). # Collatz(n)=1+Collatz(3*n+1).
@ -38,7 +39,7 @@ def collatz_length(n):
if n % 2 == 0: if n % 2 == 0:
return 1 + collatz_length(n//2) return 1 + collatz_length(n//2)
else:
return 1 + collatz_length(3*n+1) return 1 + collatz_length(3*n+1)
def main(): def main():
@ -60,9 +61,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 14') print('Project Euler, Problem 14')
print('Answer: {}'.format(max_)) print(f'Answer: {max_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,12 +1,12 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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 # 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? # How many such routes are there through a 20×20 grid?
from math import factorial from math import factorial
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -22,9 +22,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 15') print('Project Euler, Problem 15')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
# #
@ -6,6 +6,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -21,9 +22,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 16') print('Project Euler, Problem 16')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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 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.
# #
@ -9,6 +9,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -16,9 +17,9 @@ def main():
# the second letters for "twenty", "thirty", ..., "ninety", # the second letters for "twenty", "thirty", ..., "ninety",
# the third letters for "one hundred and", "two hundred and", ..., "nine hundre and", # the third letters for "one hundred and", "two hundred and", ..., "nine hundre and",
# the last one-element one the number of letters of 1000 # the last one-element one the number of letters of 1000
n_letters = [[3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8],\ n_letters = [[3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8],
[6, 6, 5, 5, 5, 7, 6, 6],\ [6, 6, 5, 5, 5, 7, 6, 6],
[13, 13, 15, 14, 14, 13, 15, 15, 14],\ [13, 13, 15, 14, 14, 13, 15, 15, 14],
[11]] [11]]
sum_ = 0 sum_ = 0
@ -59,9 +60,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 17') print('Project Euler, Problem 17')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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. # 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.
# #
@ -30,24 +30,24 @@
# NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge # NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge
# with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o) # with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)
import sys
from timeit import default_timer from timeit import default_timer
from projecteuler import find_max_path from projecteuler import find_max_path
def main(): def main():
start = default_timer() start = default_timer()
try: try:
fp = open('triang.txt', 'r') with open('triang.txt', 'r', encoding='utf-8') as fp:
except: triang = []
print('Error while opening file {}'.format('triang.txt'))
exit(1)
triang = list()
for line in fp: for line in fp:
triang.append(line.strip('\n').split()) triang.append(line.strip('\n').split())
except FileNotFoundError:
fp.close() print('Error while opening file trian.txt')
sys.exit(1)
l = len(triang) l = len(triang)
@ -60,9 +60,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 18') print('Project Euler, Problem 18')
print('Answer: {}'.format(max_)) print(f'Answer: {max_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# You are given the following information, but you may prefer to do some research for yourself. # You are given the following information, but you may prefer to do some research for yourself.
# #
@ -14,9 +14,9 @@
# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
import datetime import datetime
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -31,9 +31,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 19') print('Project Euler, Problem 19')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# n! means n × (n 1) × ... × 3 × 2 × 1 # n! means n × (n 1) × ... × 3 × 2 × 1
# #
@ -8,9 +8,9 @@
# Find the sum of the digits in the number 100! # Find the sum of the digits in the number 100!
from math import factorial from math import factorial
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -25,9 +25,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 20') print('Project Euler, Problem 20')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). # 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. # 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.
@ -8,11 +8,12 @@
# #
# Evaluate the sum of all the amicable numbers under 10000. # Evaluate the sum of all the amicable numbers under 10000.
from math import floor, sqrt
from timeit import default_timer from timeit import default_timer
from projecteuler import sum_of_divisors from projecteuler import sum_of_divisors
def main(): def main():
start = default_timer() start = default_timer()
@ -32,9 +33,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 21') print('Project Euler, Problem 21')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. # 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. # Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
@ -8,18 +8,20 @@
# #
# What is the total of all the name scores in the file? # What is the total of all the name scores in the file?
import sys
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
try: try:
fp = open('names.txt', 'r') with open('names.txt', 'r', encoding='utf-8') as fp:
except:
print('Error while opening file {}'.format('names.txt'))
exit(1)
names = list(fp.readline().replace('"', '').split(',')) names = list(fp.readline().replace('"', '').split(','))
except FileNotFoundError:
print('Error while opening file names.txt')
sys.exit(1)
names.sort() names.sort()
sum_ = 0 sum_ = 0
@ -38,9 +40,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 22') print('Project Euler, Problem 22')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. # 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. # 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.
@ -12,14 +12,15 @@
# #
# Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. # Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
from math import floor, sqrt
from timeit import default_timer from timeit import default_timer
from projecteuler import sum_of_divisors from projecteuler import sum_of_divisors
def is_abundant(n): def is_abundant(n):
return sum_of_divisors(n) > n return sum_of_divisors(n) > n
def main(): def main():
start = default_timer() start = default_timer()
@ -52,9 +53,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 23') print('Project Euler, Problem 23')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. # 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: # If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
@ -8,9 +8,9 @@
# What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? # What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
from itertools import permutations from itertools import permutations
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -21,9 +21,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 24') print('Project Euler, Problem 24')
print('Answer: {}'.format(res)) print(f'Answer: {res}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The Fibonacci sequence is defined by the recurrence relation: # The Fibonacci sequence is defined by the recurrence relation:
# #
@ -23,6 +23,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -42,9 +43,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 25') print('Project Euler, Problem 25')
print('Answer: {}'.format(i)) print(f'Answer: {i}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: # A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
# #
@ -18,6 +18,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -59,9 +60,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 26') print('Project Euler, Problem 26')
print('Answer: {}'.format(max_n)) print(f'Answer: {max_n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Euler discovered the remarkable quadratic formula: # Euler discovered the remarkable quadratic formula:
# #
@ -20,8 +20,10 @@
# 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. # 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.
from timeit import default_timer from timeit import default_timer
from projecteuler import is_prime from projecteuler import is_prime
def main(): def main():
start = default_timer() start = default_timer()
@ -52,9 +54,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 27') print('Project Euler, Problem 27')
print('Answer: {}'.format(save_a * save_b)) print(f'Answer: {save_a * save_b}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: # Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
# #
@ -14,6 +14,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -40,9 +41,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 28') print('Project Euler, Problem 28')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: # Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
# #
@ -13,9 +13,10 @@
# #
# How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? # How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
from timeit import default_timer
from numpy import zeros from numpy import zeros
from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -41,9 +42,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 29') print('Project Euler, Problem 29')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: # Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
# #
@ -14,6 +14,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -37,9 +38,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 30') print('Project Euler, Problem 30')
print('Answer: {}'.format(tot)) print(f'Answer: {tot}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: # In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
# #
@ -12,20 +12,23 @@
from timeit import default_timer from timeit import default_timer
# Simple recursive function that tries every combination. # Simple recursive function that tries every combination.
def count(coins, value, n, i): def count(coins, value, n, i):
for j in range(i, 8): for j in range(i, 8):
value = value + coins[j] value = value + coins[j]
if value == 200: if value == 200:
return n + 1 return n + 1
elif value > 200:
if value > 200:
return n return n
else:
n = count(coins, value, n, j) n = count(coins, value, n, j)
value = value - coins[j] value = value - coins[j]
return n return n
def main(): def main():
start = default_timer() start = default_timer()
@ -36,9 +39,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 31') print('Project Euler, Problem 31')
print('Answer: {}'.format(n)) print(f'Answer: {n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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, # 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. # is 1 through 5 pandigital.
@ -9,12 +9,14 @@
# #
# HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. # HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
from timeit import default_timer
import numpy as np import numpy as np
from numpy import zeros from numpy import zeros
from timeit import default_timer
from projecteuler import is_pandigital from projecteuler import is_pandigital
def main(): def main():
start = default_timer() start = default_timer()
@ -80,9 +82,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 32') print('Project Euler, Problem 32')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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, # 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. # which is correct, is obtained by cancelling the 9s.
@ -11,9 +11,9 @@
# If the product of these four fractions is given in its lowest common terms, find the value of the denominator. # If the product of these four fractions is given in its lowest common terms, find the value of the denominator.
from math import gcd from math import gcd
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -42,9 +42,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 33') print('Project Euler, Problem 33')
print('Answer: {}'.format(prod_d // div)) print(f'Answer: {prod_d // div}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. # 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
# #
@ -7,10 +7,10 @@
# Note: as 1! = 1 and 2! = 2 are not sums they are not included. # Note: as 1! = 1 and 2! = 2 are not sums they are not included.
from math import factorial from math import factorial
from timeit import default_timer
from numpy import ones from numpy import ones
from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -41,9 +41,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 34') print('Project Euler, Problem 34')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. # The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
# #
@ -7,11 +7,16 @@
# How many circular primes are there below one million? # How many circular primes are there below one million?
from timeit import default_timer from timeit import default_timer
from projecteuler import sieve from projecteuler import sieve
def is_circular_prime(n):
global primes
# Calculate all primes below one million, then check if they're circular.
N = 1000000
primes = sieve(N)
def is_circular_prime(n):
# If n is not prime, it's obviously not a circular prime. # If n is not prime, it's obviously not a circular prime.
if primes[n] == 0: if primes[n] == 0:
return False return False
@ -32,7 +37,7 @@ def is_circular_prime(n):
count = count + 1 count = count + 1
tmp = tmp // 10 tmp = tmp // 10
for i in range(1, count): for _ in range(1, count):
# Generate rotations and check if they're prime. # Generate rotations and check if they're prime.
n = n % (10 ** (count - 1)) * 10 + n // (10 ** (count - 1)) n = n % (10 ** (count - 1)) * 10 + n // (10 ** (count - 1))
@ -41,15 +46,10 @@ def is_circular_prime(n):
return True return True
def main(): def main():
start = default_timer() start = default_timer()
global primes
N = 1000000
# Calculate all primes below one million, then check if they're circular.
primes = sieve(N)
count = 13 count = 13
# Calculate all primes below one million, then check if they're circular. # Calculate all primes below one million, then check if they're circular.
@ -60,9 +60,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 35') print('Project Euler, Problem 35')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The decimal number, 585 = 1001001001_2 (binary), is palindromic in both bases. # The decimal number, 585 = 1001001001_2 (binary), is palindromic in both bases.
# #
@ -7,8 +7,10 @@
# (Please note that the palindromic number, in either base, may not include leading zeros.) # (Please note that the palindromic number, in either base, may not include leading zeros.)
from timeit import default_timer from timeit import default_timer
from projecteuler import is_palindrome from projecteuler import is_palindrome
def main(): def main():
start = default_timer() start = default_timer()
@ -26,9 +28,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 36') print('Project Euler, Problem 36')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, # 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. # and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
@ -8,8 +8,10 @@
# NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. # NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
from timeit import default_timer from timeit import default_timer
from projecteuler import is_prime from projecteuler import is_prime
def is_tr_prime(n): def is_tr_prime(n):
# One-digit numbers and non-prime numbers are # One-digit numbers and non-prime numbers are
# not truncatable primes. # not truncatable primes.
@ -40,6 +42,7 @@ def is_tr_prime(n):
# If it gets here, the number is truncatable prime. # If it gets here, the number is truncatable prime.
return True return True
def main(): def main():
start = default_timer() start = default_timer()
@ -57,9 +60,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 37') print('Project Euler, Problem 37')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Take the number 192 and multiply it by each of 1, 2, and 3: # Take the number 192 and multiply it by each of 1, 2, and 3:
# #
@ -13,11 +13,11 @@
# #
# 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? # 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?
from numpy import zeros
from timeit import default_timer from timeit import default_timer
from projecteuler import is_pandigital from projecteuler import is_pandigital
def main(): def main():
start = default_timer() start = default_timer()
@ -57,9 +57,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 38') print('Project Euler, Problem 38')
print('Answer: {}'.format(max_)) print(f'Answer: {max_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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. # 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.
# #
@ -6,9 +6,10 @@
# #
# For which value of p ≤ 1000, is the number of solutions maximised? # For which value of p ≤ 1000, is the number of solutions maximised?
from timeit import default_timer
from numpy import zeros from numpy import zeros
from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -68,9 +69,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 39') print('Project Euler, Problem 39')
print('Answer: {}'.format(res)) print(f'Answer: {res}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# An irrational decimal fraction is created by concatenating the positive integers: # An irrational decimal fraction is created by concatenating the positive integers:
# #
@ -10,9 +10,10 @@
# #
# d_1 × d_10 × d_100 × d_1000 × d_10000 × d_100000 × d_1000000 # d_1 × d_10 × d_100 × d_1000 × d_10000 × d_100000 × d_1000000
from timeit import default_timer
from numpy import zeros from numpy import zeros
from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -66,9 +67,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 40') print('Project Euler, Problem 40')
print('Answer: {}'.format(n)) print(f'Answer: {n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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 # 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. # and is also prime.
@ -6,8 +6,10 @@
# What is the largest n-digit pandigital prime that exists? # What is the largest n-digit pandigital prime that exists?
from timeit import default_timer from timeit import default_timer
from projecteuler import is_pandigital, is_prime from projecteuler import is_pandigital, is_prime
def main(): def main():
start = default_timer() start = default_timer()
@ -18,7 +20,7 @@ def main():
# until we find a prime. # until we find a prime.
i = 7654321 i = 7654321
while(i > 0): while i > 0:
if is_pandigital(i, len(str(i))) and is_prime(i): if is_pandigital(i, len(str(i))) and is_prime(i):
break break
# Skipping the even numbers. # Skipping the even numbers.
@ -27,9 +29,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 41') print('Project Euler, Problem 41')
print('Answer: {}'.format(i)) print(f'Answer: {i}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: # The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
# #
@ -10,8 +10,10 @@
# Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, # Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words,
# how many are triangle words? # how many are triangle words?
import sys
from timeit import default_timer from timeit import default_timer
def is_triang(n): def is_triang(n):
i = 1 i = 1
j = 1 j = 1
@ -24,18 +26,16 @@ def is_triang(n):
return False return False
def main(): def main():
start = default_timer() start = default_timer()
try: try:
fp = open('words.txt', 'r') with open('words.txt', 'r', encoding='utf-8') as fp:
except:
print('Error while opening file {}'.format('words.txt'))
exit(1)
words = list(fp.readline().replace('"', '').split(',')) words = list(fp.readline().replace('"', '').split(','))
except FileNotFoundError:
fp.close() print('Error while opening file words.txt')
sys.exit(1)
count = 0 count = 0
@ -53,9 +53,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 42') print('Project Euler, Problem 42')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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 # 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. # rather interesting sub-string divisibility property.
@ -16,9 +16,9 @@
# Find the sum of all 0 to 9 pandigital numbers with this property. # Find the sum of all 0 to 9 pandigital numbers with this property.
from itertools import permutations from itertools import permutations
from timeit import default_timer from timeit import default_timer
# Function to check if the value has the desired property. # Function to check if the value has the desired property.
def has_property(n): def has_property(n):
value = int(n[1]) * 100 + int(n[2]) * 10 + int(n[3]) value = int(n[1]) * 100 + int(n[2]) * 10 + int(n[3])
@ -58,6 +58,7 @@ def has_property(n):
return True return True
def main(): def main():
start = default_timer() start = default_timer()
@ -74,9 +75,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 43') print('Project Euler, Problem 43')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Pentagonal numbers are generated by the formula, Pn=n(3n1)/2. The first ten pentagonal numbers are: # Pentagonal numbers are generated by the formula, Pn=n(3n1)/2. The first ten pentagonal numbers are:
# #
@ -9,11 +9,11 @@
# Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk Pj| is minimised; # 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? # what is the value of D?
from math import sqrt
from timeit import default_timer from timeit import default_timer
from projecteuler import is_pentagonal from projecteuler import is_pentagonal
def main(): def main():
start = default_timer() start = default_timer()
@ -38,9 +38,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 44') print('Project Euler, Problem 44')
print('Answer: {}'.format(pn-pm)) print(f'Answer: {pn - pm}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: # Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
# #
@ -10,11 +10,11 @@
# #
# Find the next triangle number that is also pentagonal and hexagonal. # Find the next triangle number that is also pentagonal and hexagonal.
from math import sqrt
from timeit import default_timer from timeit import default_timer
from projecteuler import is_pentagonal from projecteuler import is_pentagonal
def main(): def main():
start = default_timer() start = default_timer()
@ -34,9 +34,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 45') print('Project Euler, Problem 45')
print('Answer: {}'.format(n)) print(f'Answer: {n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. # It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
# #
@ -14,11 +14,15 @@
# What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? # What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
from timeit import default_timer from timeit import default_timer
from projecteuler import sieve from projecteuler import sieve
def goldbach(n):
global primes
N = 10000
primes = sieve(N)
def goldbach(n):
# Check every prime smaller than n. # Check every prime smaller than n.
for i in range(3, n, 2): for i in range(3, n, 2):
if primes[i] == 1: if primes[i] == 1:
@ -43,12 +47,6 @@ def goldbach(n):
def main(): def main():
start = default_timer() start = default_timer()
global primes
N = 10000
primes = sieve(N)
found = 0 found = 0
i = 3 i = 3
@ -64,9 +62,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 46') print('Project Euler, Problem 46')
print('Answer: {}'.format(i-2)) print(f'Answer: {i - 2}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The first two consecutive numbers to have two distinct prime factors are: # The first two consecutive numbers to have two distinct prime factors are:
# #
@ -15,6 +15,7 @@
from timeit import default_timer from timeit import default_timer
# Function using a modified sieve of Eratosthenes to count # Function using a modified sieve of Eratosthenes to count
# the distinct prime factors of each number. # the distinct prime factors of each number.
def count_factors(n): def count_factors(n):
@ -29,6 +30,7 @@ def count_factors(n):
return factors return factors
def main(): def main():
start = default_timer() start = default_timer()
@ -53,9 +55,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 47') print('Project Euler, Problem 47')
print('Answer: {}'.format(res)) print(f'Answer: {res}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. # The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
# #
@ -6,6 +6,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -19,9 +20,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 48') print('Project Euler, Problem 48')
print('Answer: {}'.format(str(sum_)[-10:])) print(f'Answer: {str(sum_)[-10:]}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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, # 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. # and, (ii) each of the 4-digit numbers are permutations of one another.
@ -8,11 +8,11 @@
# #
# What 12-digit number do you form by concatenating the three terms in this sequence? # What 12-digit number do you form by concatenating the three terms in this sequence?
from numpy import zeros
from timeit import default_timer from timeit import default_timer
from projecteuler import sieve from projecteuler import sieve
def main(): def main():
start = default_timer() start = default_timer()
@ -37,16 +37,18 @@ def main():
''.join(sorted(str(i))) == ''.join(sorted(str(i+2*j))): ''.join(sorted(str(i))) == ''.join(sorted(str(i+2*j))):
found = 1 found = 1
break break
if(found): if found:
break break
i = i + 2 i = i + 2
end = default_timer() end = default_timer()
print('Project Euler, Problem 49') print('Project Euler, Problem 49')
print('Answer: {}'.format(str(i)+str(i+j)+str(i+2*j))) print(f'Answer: {str(i)+str(i+j)+str(i+2*j)}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The prime 41, can be written as the sum of six consecutive primes: # The prime 41, can be written as the sum of six consecutive primes:
# #
@ -11,8 +11,10 @@
# Which prime, below one-million, can be written as the sum of the most consecutive primes? # Which prime, below one-million, can be written as the sum of the most consecutive primes?
from timeit import default_timer from timeit import default_timer
from projecteuler import sieve from projecteuler import sieve
def main(): def main():
start = default_timer() start = default_timer()
@ -64,9 +66,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 50') print('Project Euler, Problem 50')
print('Answer: {}'.format(max_p)) print(f'Answer: {max_p}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -10,8 +10,16 @@
# value family. # value family.
from timeit import default_timer from timeit import default_timer
from projecteuler import sieve from projecteuler import sieve
N = 1000000
# N set to 1000000 as a reasonable limit, which turns out to be enough.
primes = sieve(N)
def count_digit(n, d): def count_digit(n, d):
count = 0 count = 0
@ -22,9 +30,8 @@ def count_digit(n, d):
return count return count
def replace(n):
global primes
def replace(n):
n_string = list(str(n)) n_string = list(str(n))
l = len(n_string) l = len(n_string)
max_ = 0 max_ = 0
@ -60,13 +67,6 @@ def replace(n):
def main(): def main():
start = default_timer() start = default_timer()
global primes
N = 1000000
# N set to 1000000 as a reasonable limit, which turns out to be enough.
primes = sieve(N)
# Checking only odd numbers with at least 4 digits. # Checking only odd numbers with at least 4 digits.
i = 1001 i = 1001
@ -86,9 +86,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 51') print('Project Euler, Problem 51')
print('Answer: {}'.format(i)) print(f'Answer: {i}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -4,10 +4,9 @@
# #
# Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. # Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
from numpy import zeros
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -26,9 +25,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 52') print('Project Euler, Problem 52')
print('Answer: {}'.format(i)) print(f'Answer: {i}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -12,9 +12,10 @@
# #
# How many, not necessarily distinct, values of (n r) for 1≤n≤100, are greater than one-million? # How many, not necessarily distinct, values of (n r) for 1≤n≤100, are greater than one-million?
from timeit import default_timer
from scipy.special import comb from scipy.special import comb
from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -32,9 +33,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 53') print('Project Euler, Problem 53')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -46,10 +46,11 @@
# #
# How many hands does Player 1 win? # How many hands does Player 1 win?
import sys
from enum import IntEnum from enum import IntEnum
from timeit import default_timer from timeit import default_timer
class Value(IntEnum): class Value(IntEnum):
Two = 1 Two = 1
Three = 2 Three = 2
@ -65,10 +66,11 @@ class Value(IntEnum):
King = 12 King = 12
Ace = 13 Ace = 13
class Card(): class Card():
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(Card, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.value = None self.value = None
self.suit = None self.suit = None
@ -103,20 +105,22 @@ class Card():
self.suit = card[1] self.suit = card[1]
class Hand(): class Hand():
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(Hand, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.cards = list() self.cards = list()
def sort(self): def sort(self):
self.cards.sort(key=lambda x: x.value) self.cards.sort(key=lambda x: x.value)
class Game(): class Game():
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.hand1 = None self.hand1 = None
self.hand2 = None self.hand2 = None
@ -131,6 +135,7 @@ class Game():
self.hand1.cards[0].suit == self.hand1.cards[3].suit and\ self.hand1.cards[0].suit == self.hand1.cards[3].suit and\
self.hand1.cards[0].suit == self.hand1.cards[4].suit: self.hand1.cards[0].suit == self.hand1.cards[4].suit:
return 1 return 1
# If player 2 has a Royal Flush, player 2 wins. # If player 2 has a Royal Flush, player 2 wins.
if self.hand2.cards[4].value == Value.Ace and self.hand2.cards[3].value == Value.King and\ if self.hand2.cards[4].value == Value.Ace and self.hand2.cards[3].value == Value.King and\
self.hand2.cards[2].value == Value.Queen and self.hand2.cards[1].value == Value.Jack and\ self.hand2.cards[2].value == Value.Queen and self.hand2.cards[1].value == Value.Jack and\
@ -185,7 +190,7 @@ class Game():
if straightflush1 and straightflush2: if straightflush1 and straightflush2:
if self.hand1.cards[0].value > self.hand2.cards[0].value: if self.hand1.cards[0].value > self.hand2.cards[0].value:
return 1 return 1
else:
return -1 return -1
four1 = 0 four1 = 0
@ -242,7 +247,8 @@ class Game():
if full1 and full2: if full1 and full2:
if self.hand1.cards[2].value > self.hand2.cards[2].value: if self.hand1.cards[2].value > self.hand2.cards[2].value:
return 1 return 1
elif self.hand1.cards[2].value < self.hand2.cards[2].value:
if self.hand1.cards[2].value < self.hand2.cards[2].value:
return -1 return -1
flush1 = 0 flush1 = 0
@ -323,7 +329,8 @@ class Game():
if three1 and three2: if three1 and three2:
if self.hand1.cards[2].value > self.hand2.cards[2].value: if self.hand1.cards[2].value > self.hand2.cards[2].value:
return 1 return 1
elif self.hand1.cards[2].value < self.hand2.cards[2].value:
if self.hand1.cards[2].value < self.hand2.cards[2].value:
return -1 return -1
twopairs1 = 0 twopairs1 = 0
@ -354,17 +361,21 @@ class Game():
if twopairs1 and twopairs2: if twopairs1 and twopairs2:
if self.hand1.cards[3].value > self.hand2.cards[3].value: if self.hand1.cards[3].value > self.hand2.cards[3].value:
return 1 return 1
elif self.hand1.cards[3].value < self.hand2.cards[3].value:
if self.hand1.cards[3].value < self.hand2.cards[3].value:
return -1 return -1
elif self.hand1.cards[1].value > self.hand2.cards[1].value:
if self.hand1.cards[1].value > self.hand2.cards[1].value:
return 1 return 1
elif self.hand1.cards[1].value < self.hand2.cards[1].value:
if self.hand1.cards[1].value < self.hand2.cards[1].value:
return -1 return -1
for i in range(4, -1, -1): for i in range(4, -1, -1):
if self.hand1.cards[i].value > self.hand2.cards[i].value: if self.hand1.cards[i].value > self.hand2.cards[i].value:
return 1 return 1
elif self.hand1.cards[i].value < self.hand2.cards[i].value:
if self.hand1.cards[i].value < self.hand2.cards[i].value:
return -1 return -1
pair1 = 0 pair1 = 0
@ -431,18 +442,16 @@ class Game():
# If everything is equal, return 0 # If everything is equal, return 0
return 0 return 0
def main(): def main():
start = default_timer() start = default_timer()
try: try:
fp = open('poker.txt', 'r') with open('poker.txt', 'r', encoding='utf-8') as fp:
except:
print('Error while opening file {}'.format('poker.txt'))
exit(1)
games = fp.readlines() games = fp.readlines()
except FileNotFoundError:
fp.close() print('Error while opening file poker.txt')
sys.exit(1)
count = 0 count = 0
@ -478,9 +487,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 54') print('Project Euler, Problem 54')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -24,13 +24,15 @@
# NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers. # NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.
from timeit import default_timer from timeit import default_timer
from projecteuler import is_palindrome from projecteuler import is_palindrome
def is_lychrel(n): def is_lychrel(n):
tmp = n tmp = n
# Run for 50 iterations # Run for 50 iterations
for i in range(50): for _ in range(50):
reverse = 0 reverse = 0
# Find the reverse of the given number # Find the reverse of the given number
@ -50,6 +52,7 @@ def is_lychrel(n):
return True return True
def main(): def main():
start = default_timer() start = default_timer()
@ -64,9 +67,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 55') print('Project Euler, Problem 55')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -7,6 +7,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -28,9 +29,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 56') print('Project Euler, Problem 56')
print('Answer: {}'.format(max_)) print(f'Answer: {max_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -18,6 +18,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -27,7 +28,7 @@ def main():
# If n/d is the current term of the expansion, the next term can be calculated as # If n/d is the current term of the expansion, the next term can be calculated as
# (n+2d)/(n+d). # (n+2d)/(n+d).
for i in range(1, 1000): for _ in range(1, 1000):
d2 = 2 * d d2 = 2 * d
d = n + d d = n + d
n = n + d2 n = n + d2
@ -38,9 +39,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 57') print('Project Euler, Problem 57')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -17,8 +17,10 @@
# what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? # what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?
from timeit import default_timer from timeit import default_timer
from projecteuler import is_prime from projecteuler import is_prime
def main(): def main():
start = default_timer() start = default_timer()
@ -62,9 +64,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 58') print('Project Euler, Problem 58')
print('Answer: {}'.format(l)) print(f'Answer: {l}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -20,26 +20,26 @@
from timeit import default_timer from timeit import default_timer
class EncryptedText(): class EncryptedText():
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(EncryptedText, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.text = None self.text = None
self.len = 0 self.len = 0
def read_text(self, filename): def read_text(self, filename):
try: try:
fp = open(filename, 'r') with open(filename, 'r', encoding='utf-8') as fp:
except: self.text = list(map(int, list(fp.readline().split(','))))
print('Error while opening file {}'.format(filename)) except FileNotFoundError:
print(f'Error while opening file {filename}')
return -1 return -1
self.text = list(map(int, list(fp.readline().split(','))))
self.len = len(self.text) self.len = len(self.text)
fp.close()
def decrypt(self): def decrypt(self):
found = 0 found = 0
@ -49,10 +49,13 @@ class EncryptedText():
for c2 in range(ord('a'), ord('z')+1): for c2 in range(ord('a'), ord('z')+1):
if found: if found:
break break
for c3 in range(ord('a'), ord('z')+1): for c3 in range(ord('a'), ord('z')+1):
if found: if found:
break break
plain_text = [''] * self.len plain_text = [''] * self.len
for i in range(0, self.len-2, 3): for i in range(0, self.len-2, 3):
plain_text[i] = str(chr(self.text[i]^c1)) plain_text[i] = str(chr(self.text[i]^c1))
plain_text[i+1] = str(chr(self.text[i+1]^c2)) plain_text[i+1] = str(chr(self.text[i+1]^c2))
@ -73,13 +76,14 @@ class EncryptedText():
return plain_text return plain_text
def main(): def main():
start = default_timer() start = default_timer()
enc_text = EncryptedText() enc_text = EncryptedText()
if enc_text.read_text('cipher.txt') == -1: if enc_text.read_text('cipher.txt') == -1:
exit(1) sys.exit(1)
plain_text = enc_text.decrypt() plain_text = enc_text.decrypt()
@ -91,9 +95,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 59') print('Project Euler, Problem 59')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -7,8 +7,10 @@
# Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. # Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
from timeit import default_timer from timeit import default_timer
from projecteuler import sieve, is_prime from projecteuler import sieve, is_prime
def main(): def main():
start = default_timer() start = default_timer()
@ -43,6 +45,7 @@ def main():
if primes[p3] == 0 or not is_prime(int(str(p1)+str(p3))) or not is_prime(int(str(p3)+str(p1))) or\ if primes[p3] == 0 or not is_prime(int(str(p1)+str(p3))) or not is_prime(int(str(p3)+str(p1))) or\
not is_prime(int(str(p2)+str(p3))) or not is_prime(int(str(p3)+str(p2))): not is_prime(int(str(p2)+str(p3))) or not is_prime(int(str(p3)+str(p2))):
p3 = p3 + 2 p3 = p3 + 2
continue continue
p4 = p3 + 2 p4 = p3 + 2
@ -54,6 +57,7 @@ def main():
not is_prime(int(str(p2)+str(p4))) or not is_prime(int(str(p4)+str(p2))) or\ not is_prime(int(str(p2)+str(p4))) or not is_prime(int(str(p4)+str(p2))) or\
not is_prime(int(str(p3)+str(p4))) or not is_prime(int(str(p4)+str(p3))): not is_prime(int(str(p3)+str(p4))) or not is_prime(int(str(p4)+str(p3))):
p4 = p4 + 2 p4 = p4 + 2
continue continue
p5 = p4 + 2 p5 = p4 + 2
@ -66,6 +70,7 @@ def main():
not is_prime(int(str(p3)+str(p5))) or not is_prime(int(str(p5)+str(p3))) or\ not is_prime(int(str(p3)+str(p5))) or not is_prime(int(str(p5)+str(p3))) or\
not is_prime(int(str(p4)+str(p5))) or not is_prime(int(str(p5)+str(p4))): not is_prime(int(str(p4)+str(p5))) or not is_prime(int(str(p5)+str(p4))):
p5 = p5 + 2 p5 = p5 + 2
continue continue
# If it gets here, the five values have been found. # If it gets here, the five values have been found.
@ -83,9 +88,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 60') print('Project Euler, Problem 60')
print('Answer: {}'.format(n)) print(f'Answer: {n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated # Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated
# by the following formulae: # by the following formulae:
@ -19,18 +19,22 @@
# Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, # Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal,
# hexagonal, heptagonal, and octagonal, is represented by a different number in the set. # hexagonal, heptagonal, and octagonal, is represented by a different number in the set.
from timeit import default_timer
from numpy import zeros from numpy import zeros
from timeit import default_timer
polygonal = zeros((6, 10000), int)
chain = [0] * 6
flags = [0] * 6
sum_ = 0
# Recursive function to find the required set. It finds a polygonal number, # Recursive function to find the required set. It finds a polygonal number,
# check if it can be part of the chain, then use recursion to find the next # check if it can be part of the chain, then use recursion to find the next
# number. If a solution can't be found with the current numbers, it uses # number. If a solution can't be found with the current numbers, it uses
# backtracking and tries the next polygonal number. # backtracking and tries the next polygonal number.
def find_set(step): def find_set(step):
global polygonal
global chain
global flags
global sum_ global sum_
# Use one polygonal number per type, starting from triangular. # Use one polygonal number per type, starting from triangular.
@ -49,7 +53,7 @@ def find_set(step):
# If it's the first number, just add it as first step in the chain. # If it's the first number, just add it as first step in the chain.
if step == 0: if step == 0:
chain[step] = j chain[step] = j
sum_ = sum_ + j sum_ += j
# Recursively try to add other numbers to the chain. If a solution # Recursively try to add other numbers to the chain. If a solution
# is found, return 1. # is found, return 1.
@ -58,42 +62,34 @@ def find_set(step):
# If a solution was not found, backtrack, subtracting the value of # If a solution was not found, backtrack, subtracting the value of
# the number from the total. # the number from the total.
sum_ = sum_ - j sum_ -= j
# If this is the last step and the current number can be added to the chain, # If this is the last step and the current number can be added to the chain,
# add it, update the sum and return 1. A solution has been found. # add it, update the sum and return 1. A solution has been found.
elif step == 5 and j % 100 == chain[0] // 100 and j // 100 == chain[step-1] % 100: elif step == 5 and j % 100 == chain[0] // 100 and j // 100 == chain[step-1] % 100:
chain[step] = j chain[step] = j
sum_ = sum_ + j sum_ += j
return 1 return 1
# For every other step, add the number to the chain if possible, then recursively # For every other step, add the number to the chain if possible, then recursively
# try to add other numbers. # try to add other numbers.
elif step < 5 and j // 100 == chain[step-1] % 100: elif step < 5 and j // 100 == chain[step-1] % 100:
chain[step] = j chain[step] = j
sum_ = sum_ + j sum_ += + j
if find_set(step+1): if find_set(step+1):
return 1 return 1
# If a solution was not found, backtrack. # If a solution was not found, backtrack.
sum_ = sum_ - j sum_ -= j
# Remove the flag for the current polygonal type. # Remove the flag for the current polygonal type.
flags[i] = 0 flags[i] = 0
return 0 return 0
def main(): def main():
start = default_timer() start = default_timer()
global polygonal
global chain
global flags
global sum_
polygonal = zeros((6, 10000), int)
chain = [0] * 6
flags = [0] * 6
sum_ = 0
i = 1 i = 1
n = 1 n = 1
@ -172,9 +168,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 61') print('Project Euler, Problem 61')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -5,9 +5,10 @@
# #
# Find the smallest cube for which exactly five permutations of its digits are cube. # Find the smallest cube for which exactly five permutations of its digits are cube.
from timeit import default_timer
from numpy import zeros from numpy import zeros
from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -45,9 +46,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 62') print('Project Euler, Problem 62')
print('Answer: {}'.format(cubes[i])) print(f'Answer: {cubes[i]}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -6,6 +6,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -30,9 +31,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 63') print('Project Euler, Problem 63')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -42,19 +42,18 @@
# #
# How many continued fractions for N≤10000 have an odd period? # How many continued fractions for N≤10000 have an odd period?
from math import floor, sqrt from math import sqrt
from timeit import default_timer from timeit import default_timer
from projecteuler import build_sqrt_cont_fraction from projecteuler import build_sqrt_cont_fraction
def is_square(n): def is_square(n):
p = sqrt(n) p = sqrt(n)
m = int(p) m = int(p)
if p == m: return bool(p == m)
return True
else:
return False
def main(): def main():
start = default_timer() start = default_timer()
@ -74,9 +73,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 64') print('Project Euler, Problem 64')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -31,6 +31,7 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -70,9 +71,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 65') print('Project Euler, Problem 65')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -21,18 +21,17 @@
# Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained. # Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained.
from math import sqrt from math import sqrt
from timeit import default_timer from timeit import default_timer
from projecteuler import pell_eq from projecteuler import pell_eq
def is_square(n): def is_square(n):
p = sqrt(n) p = sqrt(n)
m = int(p) m = int(p)
if p == m: return bool(p == m)
return True
else:
return False
def main(): def main():
start = default_timer() start = default_timer()
@ -52,9 +51,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 66') print('Project Euler, Problem 66')
print('Answer: {}'.format(max_d)) print(f'Answer: {max_d}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# 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. # 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.
# #
@ -15,24 +15,24 @@
# If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. # If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all.
# There is an efficient algorithm to solve it. ;o) # There is an efficient algorithm to solve it. ;o)
import sys
from timeit import default_timer from timeit import default_timer
from projecteuler import find_max_path from projecteuler import find_max_path
def main(): def main():
start = default_timer() start = default_timer()
triang = []
try: try:
fp = open('triangle.txt', 'r') with open('triangle.txt', 'r', encoding='utf-8') as fp:
except:
print('Error while opening file {}'.format('triangle.txt'))
exit(1)
triang = list()
for line in fp: for line in fp:
triang.append(line.strip('\n').split()) triang.append(line.strip('\n').split())
except FileNotFoundError:
fp.close() print('Error while opening file triangle.txt')
sys.exit(1)
l = len(triang) l = len(triang)
@ -45,9 +45,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 67') print('Project Euler, Problem 67')
print('Answer: {}'.format(max_)) print(f'Answer: {max_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each line adding to nine. # Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each line adding to nine.
# #
@ -46,9 +46,9 @@
# #
from itertools import permutations from itertools import permutations
from timeit import default_timer from timeit import default_timer
# Function to evaluate the ring. The ring is represented as a vector of 2*n elements, # Function to evaluate the ring. The ring is represented as a vector of 2*n elements,
# the first n elements represent the external nodes of the ring, the next n elements # the first n elements represent the external nodes of the ring, the next n elements
# represent the internal ring. # represent the internal ring.
@ -91,8 +91,9 @@ def eval_ring(ring, n):
return res return res
def list_to_int(l): def list_to_int(l):
if l == None: if l is None:
return 0 return 0
res = 0 res = 0
@ -108,6 +109,7 @@ def list_to_int(l):
return res return res
def main(): def main():
start = default_timer() start = default_timer()
@ -118,7 +120,7 @@ def main():
n = None n = None
for ring in rings: for ring in rings:
eval_ = eval_ring(ring, 5); eval_ = eval_ring(ring, 5)
# Convert the list into an integer number. # Convert the list into an integer number.
n = list_to_int(eval_) n = list_to_int(eval_)
@ -129,9 +131,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 68') print('Project Euler, Problem 68')
print('Answer: {}'.format(max_)) print(f'Answer: {max_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of numbers less than n which are # Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of numbers less than n which are
# relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6. # relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6.
@ -19,8 +19,10 @@
# Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum. # Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.
from timeit import default_timer from timeit import default_timer
from projecteuler import is_prime from projecteuler import is_prime
def main(): def main():
start = default_timer() start = default_timer()
@ -47,9 +49,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 69') print('Project Euler, Problem 69')
print('Answer: {}'.format(res)) print(f'Answer: {res}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of positive numbers # Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of positive numbers
# less than or equal to n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and # less than or equal to n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and
@ -9,11 +9,11 @@
# #
# Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum. # Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum.
from numpy import zeros
from timeit import default_timer from timeit import default_timer
from projecteuler import sieve, is_semiprime, phi_semiprime from projecteuler import sieve, is_semiprime, phi_semiprime
def main(): def main():
start = default_timer() start = default_timer()
@ -33,7 +33,7 @@ def main():
# smaller. # smaller.
semi_p, a, b = is_semiprime(i, primes) semi_p, a, b = is_semiprime(i, primes)
if semi_p == True: if semi_p is True:
p = phi_semiprime(i, a, b) p = phi_semiprime(i, a, b)
if ''.join(sorted(str(p))) == ''.join(sorted(str(i))) and i / p < min_: if ''.join(sorted(str(p))) == ''.join(sorted(str(i))) and i / p < min_:
@ -43,9 +43,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 70') print('Project Euler, Problem 70')
print('Answer: {}'.format(n)) print(f'Answer: {n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. # Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
# #
@ -12,9 +12,9 @@
# of the fraction immediately to the left of 3/7. # of the fraction immediately to the left of 3/7.
from math import gcd from math import gcd
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -46,9 +46,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 71') print('Project Euler, Problem 71')
print('Answer: {}'.format(max_n)) print(f'Answer: {max_n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. # Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
# #
@ -11,8 +11,10 @@
# How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000? # How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000?
from timeit import default_timer from timeit import default_timer
from projecteuler import sieve, phi from projecteuler import sieve, phi
def main(): def main():
start = default_timer() start = default_timer()
@ -31,9 +33,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 72') print('Project Euler, Problem 72')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. # Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
# #
@ -11,9 +11,9 @@
# How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ 12,000? # How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ 12,000?
from math import gcd from math import gcd
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -33,9 +33,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 73') print('Project Euler, Problem 73')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: # The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:
# #
@ -23,13 +23,14 @@
# How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? # How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?
from math import factorial from math import factorial
from timeit import default_timer from timeit import default_timer
def len_chain(n):
global N
global chains
N = 1000000
chains = [0] * N
def len_chain(n):
chain = [0] * 60 chain = [0] * 60
count = 0 count = 0
finished = 0 finished = 0
@ -68,16 +69,10 @@ def len_chain(n):
return count return count
def main(): def main():
start = default_timer() start = default_timer()
global N
global chains
N = 1000000
chains = [0] * N
count = 0 count = 0
# Simple brute force approach, for every number calculate # Simple brute force approach, for every number calculate
@ -89,9 +84,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 74') print('Project Euler, Problem 74')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, # It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way,
# but there are many more examples. # but there are many more examples.
@ -18,9 +18,9 @@
# Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed? # Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed?
from math import gcd from math import gcd
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -46,7 +46,7 @@ def main():
b = 2 * m * n b = 2 * m * n
c = m * m + n * n c = m * m + n * n
if(a + b + c <= N): if a + b + c <= N:
l[a+b+c] = l[a+b+c] + 1 l[a+b+c] = l[a+b+c] + 1
i = 2 i = 2
@ -54,7 +54,7 @@ def main():
tmpb = i * b tmpb = i * b
tmpc = i * c tmpc = i * c
while(tmpa + tmpb + tmpc <= N): while tmpa + tmpb + tmpc <= N:
l[tmpa+tmpb+tmpc] = l[tmpa+tmpb+tmpc] + 1 l[tmpa+tmpb+tmpc] = l[tmpa+tmpb+tmpc] + 1
i = i + 1 i = i + 1
@ -71,9 +71,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 75') print('Project Euler, Problem 75')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,8 +1,21 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# It is possible to write five as a sum in exactly six different ways:
#
# 4 + 1
# 3 + 2
# 3 + 1 + 1
# 2 + 2 + 1
# 2 + 1 + 1 + 1
# 1 + 1 + 1 + 1 + 1
#
# How many different ways can one hundred be written as a sum of at least two positive integers?*/
from timeit import default_timer from timeit import default_timer
from projecteuler import partition_fn from projecteuler import partition_fn
def main(): def main():
start = default_timer() start = default_timer()
@ -16,9 +29,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 76') print('Project Euler, Problem 76')
print('Answer: {}'.format(n)) print(f'Answer: {n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -11,33 +11,34 @@
# What is the first value which can be written as the sum of primes in over five thousand different ways? # What is the first value which can be written as the sum of primes in over five thousand different ways?
from timeit import default_timer from timeit import default_timer
from projecteuler import is_prime from projecteuler import is_prime
primes = [0] * 100
# Function using a simple recursive brute force approach # Function using a simple recursive brute force approach
# to find all the partitions. # to find all the partitions.
def count(value, n, i, target): def count(value, n, i, target):
global primes
for j in range(i, 100): for j in range(i, 100):
value = value + primes[j] value = value + primes[j]
if value == target: if value == target:
return n + 1 return n + 1
elif value > target:
if value > target:
return n return n
else:
n = count(value, n, j, target) n = count(value, n, j, target)
value = value - primes[j] value = value - primes[j]
return n return n
def main(): def main():
start = default_timer() start = default_timer()
global primes
primes = [0] * 100
# Generate a list of the first 100 primes. # Generate a list of the first 100 primes.
i = 0 i = 0
j = 0 j = 0
@ -64,9 +65,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 77') print('Project Euler, Problem 77')
print('Answer: {}'.format(i)) print(f'Answer: {i}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -14,8 +14,10 @@
# Find the least value of n for which p(n) is divisible by one million. # Find the least value of n for which p(n) is divisible by one million.
from timeit import default_timer from timeit import default_timer
from projecteuler import partition_fn from projecteuler import partition_fn
def main(): def main():
start = default_timer() start = default_timer()
@ -33,9 +35,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 78') print('Project Euler, Problem 78')
print('Answer: {}'.format(i)) print(f'Answer: {i}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -8,10 +8,11 @@
# Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible # Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible
# secret passcode of unknown length. # secret passcode of unknown length.
import sys
from itertools import permutations from itertools import permutations
from timeit import default_timer from timeit import default_timer
def check_passcode(passcode, len_, logins, n): def check_passcode(passcode, len_, logins, n):
# For every login attempt, check if all the digits appear in the # For every login attempt, check if all the digits appear in the
# passcode in the correct order. Return 0 if a login attempt # passcode in the correct order. Return 0 if a login attempt
@ -30,18 +31,16 @@ def check_passcode(passcode, len_, logins, n):
return 1 return 1
def main(): def main():
start = default_timer() start = default_timer()
try: try:
fp = open('keylog.txt', 'r') with open('keylog.txt', 'r', encoding='utf-8') as fp:
except:
print('Error while opening file {}'.format('keylog.txt'))
exit(1)
logins = fp.readlines() logins = fp.readlines()
except FileNotFoundError:
fp.close() print('Error while opening file keylog.txt')
sys.exit(1)
digits = [0] * 10 digits = [0] * 10
passcode_digits = [0] * 10 passcode_digits = [0] * 10
@ -97,9 +96,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 79') print('Project Euler, Problem 79')
print('Answer: {}'.format(res)) print(f'Answer: {res}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -8,18 +8,16 @@
# For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits # For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits
# for all the irrational square roots # for all the irrational square roots
from timeit import default_timer
from mpmath import sqrt, mp from mpmath import sqrt, mp
from timeit import default_timer
def is_square(n): def is_square(n):
p = sqrt(n) p = sqrt(n)
m = int(p) m = int(p)
if p == m: return bool(p == m)
return True
else:
return False
def main(): def main():
start = default_timer() start = default_timer()
@ -43,9 +41,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 80') print('Project Euler, Problem 80')
print('Answer: {}'.format(sum_)) print(f'Answer: {sum_}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -12,8 +12,10 @@
# Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right # Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right
# by only moving right and down. # by only moving right and down.
import sys
from timeit import default_timer from timeit import default_timer
def sum_paths(matrix, m, n): def sum_paths(matrix, m, n):
for i in range(m-2, -1, -1): for i in range(m-2, -1, -1):
matrix[m-1][i] = matrix[m-1][i] + matrix[m-1][i+1] matrix[m-1][i] = matrix[m-1][i] + matrix[m-1][i+1]
@ -28,20 +30,19 @@ def sum_paths(matrix, m, n):
return matrix[0][0] return matrix[0][0]
def main(): def main():
start = default_timer() start = default_timer()
try: try:
fp = open('matrix.txt', 'r') with open('matrix.txt', 'r', encoding='utf-8') as fp:
except:
print('Error while opening file {}'.format('matrix.txt'))
exit(1)
matrix = fp.readlines() matrix = fp.readlines()
except FileNotFoundError:
fp.close() print('Error while opening file matrix.txt')
sys.exit(1)
j = 0 j = 0
for i in matrix: for i in matrix:
matrix[j] = list(map(int, i.strip().split(','))) matrix[j] = list(map(int, i.strip().split(',')))
j = j + 1 j = j + 1
@ -51,9 +52,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 81') print('Project Euler, Problem 81')
print('Answer: {}'.format(dist)) print(f'Answer: {dist}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -15,24 +15,28 @@
# #
# Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, from the left column to the right column. # Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, from the left column to the right column.
import sys
from timeit import default_timer
from numpy import zeros from numpy import zeros
from timeit import default_timer
from projecteuler import dijkstra from projecteuler import dijkstra
def main(): def main():
start = default_timer() start = default_timer()
try: try:
fp = open('matrix.txt', 'r') with open('matrix.txt', 'r', encoding='utf-8') as fp:
except:
print('Error while opening file {}'.format('matrix.txt'))
exit(1)
matrix = fp.readlines() matrix = fp.readlines()
except FileNotFoundError:
print('Error while opening file matrix.txt')
sys.exit(1)
distances = zeros((80, 80), int) distances = zeros((80, 80), int)
j = 0 j = 0
for i in matrix: for i in matrix:
matrix[j] = list(map(int, i.strip().split(','))) matrix[j] = list(map(int, i.strip().split(',')))
j = j + 1 j = j + 1
@ -53,9 +57,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 82') print('Project Euler, Problem 82')
print('Answer: {}'.format(min_path)) print(f'Answer: {min_path}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -14,21 +14,24 @@
# Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, # Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix,
# from the top left to the bottom right by moving left, right, up, and down. # from the top left to the bottom right by moving left, right, up, and down.
import sys
from timeit import default_timer
from numpy import zeros from numpy import zeros
from timeit import default_timer
from projecteuler import dijkstra from projecteuler import dijkstra
def main(): def main():
start = default_timer() start = default_timer()
try: try:
fp = open('matrix.txt', 'r') with open('matrix.txt', 'r', encoding='utf-8') as fp:
except:
print('Error while opening file {}'.format('matrix.txt'))
exit(1)
matrix = fp.readlines() matrix = fp.readlines()
except FileNotFoundError:
print('Error while opening file matrix.txt')
sys.exit(1)
distances = zeros((80, 80), int) distances = zeros((80, 80), int)
j = 0 j = 0
@ -43,9 +46,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 83') print('Project Euler, Problem 83')
print('Answer: {}'.format(dist)) print(f'Answer: {dist}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,3 +1,5 @@
#! /usr/bin/env python3
# The Fibonacci sequence is defined by the recurrence relation: # The Fibonacci sequence is defined by the recurrence relation:
# #
# F_n = F_n1 + F_n2, where F_1 = 1 and F_2 = 1. # F_n = F_n1 + F_n2, where F_1 = 1 and F_2 = 1.
@ -7,13 +9,17 @@
# #
# Given that F_k is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k. # Given that F_k is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k.
#!/usr/bin/python import sys
from mpmath import matrix, mp
from timeit import default_timer from timeit import default_timer
from mpmath import matrix
from projecteuler import is_pandigital from projecteuler import is_pandigital
sys.set_int_max_str_digits(70000)
def main(): def main():
start = default_timer() start = default_timer()
@ -49,9 +55,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 104') print('Project Euler, Problem 104')
print('Answer: {}'.format(i)) print(f'Answer: {i}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -10,10 +10,11 @@
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
N = 10000000 N = 1000000000
count = 0 count = 0
@ -23,16 +24,17 @@ def main():
if i % 10 != 0: if i % 10 != 0:
s = str(i + int(''.join(reversed(str(i))))) s = str(i + int(''.join(reversed(str(i)))))
if not '0' in s and not '2' in s and not '4' in s and\ if '0' not in s and '2' not in s and '4' not in s and\
not '6' in s and not '8' in s: '6' not in s and '8' not in s:
count = count + 1 count = count + 1
end = default_timer() end = default_timer()
print('Project Euler, Problem 145') print('Project Euler, Problem 145')
print('Answer: {}'.format(count)) print(f'Answer: {count}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,10 +1,11 @@
#!/usr/bin/python3 #!/usr/bin/env python3
# Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, # Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,
# where each “_” is a single digit. # where each “_” is a single digit.
from timeit import default_timer from timeit import default_timer
def main(): def main():
start = default_timer() start = default_timer()
@ -37,10 +38,10 @@ def main():
end = default_timer() end = default_timer()
print('Project Euler, Problem 206') print('Project Euler, Problem 206')
print('Answer: {}'.format(n)) print(f'Answer: {n}')
print(f'Elapsed time: {end - start:.9f} seconds')
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3 #!/usr/bin/env python3
from math import sqrt, floor, ceil, gcd from math import sqrt, floor, ceil, gcd

View File

@ -1,3 +1,6 @@
# My Project Euler solutions # My Project Euler solutions
These are my solutions in C and Python, not necessarily the best solutions. I've solved most of the first 100 problems, currently working on cleaning the code and uploading it. I will try to solve more problems in the future. These are my solutions in C and Python, not necessarily the best solutions. I've solved most of the first 100 problems, currently working on cleaning the code and uploading it. I will try to solve more problems in the future.
# Issues
- Solutions for problems 82 and 145 in Python run really slow.
- Solutions for problems 84, 85, 86, 87, 89, 92, 95, 96, 97. 99, 102, 112, 124 and 357 have been implemented in C but not in Python.