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.
#
@ -6,6 +6,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -20,9 +21,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -8,6 +8,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -32,9 +33,10 @@ def main():
end = default_timer()
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__':
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.
#
# What is the largest prime factor of the number 600851475143?
from math import floor, sqrt
from timeit import default_timer
from projecteuler import is_prime
# Recursive approach: if num is prime, return num, otherwise
# recursively look for the largest prime factor of num divided
# by its prime factors until only the largest remains.
@ -21,20 +21,21 @@ def max_prime_factor(num):
if num % 2 == 0:
return max_prime_factor(num // 2)
else:
i = 3
i = 3
# If num is divisible by i and i is prime, find largest
# prime factor of num/i.
while True:
if num % i == 0:
if is_prime(i):
return max_prime_factor(num//i)
i = i + 2
# If num is divisible by i and i is prime, find largest
# prime factor of num/i.
while True:
if num % i == 0:
if is_prime(i):
return max_prime_factor(num//i)
i = i + 2
# Should never get here
return -1
def main():
start = default_timer()
@ -43,9 +44,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -7,6 +7,7 @@
from timeit import default_timer
from projecteuler import is_palindrome
def main():
start = default_timer()
@ -25,9 +26,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -7,6 +7,7 @@
from timeit import default_timer
from projecteuler import lcmm
def main():
start = default_timer()
@ -19,9 +20,10 @@ def main():
end = default_timer()
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__':
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,
#
@ -14,6 +14,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -30,9 +31,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -7,6 +7,7 @@
from timeit import default_timer
from projecteuler import is_prime
def main():
start = default_timer()
@ -25,9 +26,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -27,6 +27,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -69,9 +70,10 @@ def main():
end = default_timer()
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__':
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,
#
@ -11,9 +11,9 @@
# Find the product abc.
from math import gcd
from timeit import default_timer
def main():
start = default_timer()
@ -61,9 +61,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -7,12 +7,13 @@
from timeit import default_timer
from projecteuler import sieve
def main():
start = default_timer()
N = 2000000
# Use the function in projecteuler.py implementing the
# Use the function in projecteuler.py implementing the
# Sieve of Eratosthenes algorithm to generate primes.
primes = sieve(N)
sum_ = 0
@ -25,9 +26,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -29,6 +29,7 @@
from timeit import default_timer
def main():
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],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]];
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]]
max_ = 0
@ -112,9 +113,10 @@ def main():
end = default_timer()
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__':
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 first ten terms would be:
@ -22,6 +22,7 @@
from timeit import default_timer
from projecteuler import count_divisors
def main():
start = default_timer()
@ -41,9 +42,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -103,9 +103,9 @@
# 20849603980134001723930671666823555245252804609722
# 53503534226472524250874054075591789781264330331690
from timeit import default_timer
import numpy as np
from timeit import default_timer
def main():
start = default_timer()
@ -219,9 +219,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -16,13 +16,14 @@
#
# NOTE: Once the chain starts the terms are allowed to go above one million.
from timeit import default_timer
from numpy import zeros
from timeit import default_timer
N = 1000000
collatz_found = zeros(N, dtype=int)
# Recursive function to calculate the Collatz sequence for n.
# If n is even, Collatz(n)=1+Collatz(n/2), if n is odd
# Collatz(n)=1+Collatz(3*n+1).
@ -38,8 +39,8 @@ def collatz_length(n):
if n % 2 == 0:
return 1 + collatz_length(n//2)
else:
return 1 + collatz_length(3*n+1)
return 1 + collatz_length(3*n+1)
def main():
start = default_timer()
@ -60,9 +61,10 @@ def main():
end = default_timer()
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__':
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
# How many such routes are there through a 20×20 grid?
from math import factorial
from timeit import default_timer
def main():
start = default_timer()
@ -22,9 +22,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -6,6 +6,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -21,9 +22,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -9,6 +9,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -16,10 +17,10 @@ def main():
# the second letters for "twenty", "thirty", ..., "ninety",
# the third letters for "one hundred and", "two hundred and", ..., "nine hundre and",
# 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],\
[6, 6, 5, 5, 5, 7, 6, 6],\
[13, 13, 15, 14, 14, 13, 15, 15, 14],\
[11]]
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],
[13, 13, 15, 14, 14, 13, 15, 15, 14],
[11]]
sum_ = 0
@ -59,9 +60,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -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
# 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 projecteuler import find_max_path
def main():
start = default_timer()
try:
fp = open('triang.txt', 'r')
except:
print('Error while opening file {}'.format('triang.txt'))
exit(1)
with open('triang.txt', 'r', encoding='utf-8') as fp:
triang = []
triang = list()
for line in fp:
triang.append(line.strip('\n').split())
fp.close()
for line in fp:
triang.append(line.strip('\n').split())
except FileNotFoundError:
print('Error while opening file trian.txt')
sys.exit(1)
l = len(triang)
@ -60,9 +60,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -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)?
import datetime
from timeit import default_timer
def main():
start = default_timer()
@ -31,9 +31,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3
#!/usr/bin/env python3
# n! means n × (n 1) × ... × 3 × 2 × 1
#
@ -8,9 +8,9 @@
# Find the sum of the digits in the number 100!
from math import factorial
from timeit import default_timer
def main():
start = default_timer()
@ -25,9 +25,10 @@ def main():
end = default_timer()
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__':
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).
# 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.
from math import floor, sqrt
from timeit import default_timer
from projecteuler import sum_of_divisors
def main():
start = default_timer()
@ -32,9 +33,10 @@ def main():
end = default_timer()
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__':
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.
# 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?
import sys
from timeit import default_timer
def main():
start = default_timer()
try:
fp = open('names.txt', 'r')
except:
print('Error while opening file {}'.format('names.txt'))
exit(1)
with open('names.txt', 'r', encoding='utf-8') as fp:
names = list(fp.readline().replace('"', '').split(','))
except FileNotFoundError:
print('Error while opening file names.txt')
sys.exit(1)
names = list(fp.readline().replace('"', '').split(','))
names.sort()
sum_ = 0
@ -38,9 +40,10 @@ def main():
end = default_timer()
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__':
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.
# 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.
from math import floor, sqrt
from timeit import default_timer
from projecteuler import sum_of_divisors
def is_abundant(n):
return sum_of_divisors(n) > n
def main():
start = default_timer()
@ -52,9 +53,10 @@ def main():
end = default_timer()
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__':
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.
# 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?
from itertools import permutations
from timeit import default_timer
def main():
start = default_timer()
@ -21,9 +21,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3
#!/usr/bin/env python3
# The Fibonacci sequence is defined by the recurrence relation:
#
@ -23,6 +23,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -42,9 +43,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -18,6 +18,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -59,9 +60,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -1,4 +1,4 @@
#!/usr/bin/python3
#!/usr/bin/env python3
# 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.
from timeit import default_timer
from projecteuler import is_prime
def main():
start = default_timer()
@ -52,9 +54,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -14,6 +14,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -40,9 +41,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -13,9 +13,10 @@
#
# 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 timeit import default_timer
def main():
start = default_timer()
@ -31,7 +32,7 @@ def main():
# Sort the values and count the different values.
powers = list(powers)
powers.sort()
count = 1
for i in range(1, 9801):
@ -41,9 +42,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -14,6 +14,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -37,9 +38,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -12,20 +12,23 @@
from timeit import default_timer
# Simple recursive function that tries every combination.
def count(coins, value, n, i):
for j in range(i, 8):
value = value + coins[j]
if value == 200:
return n + 1
elif value > 200:
if value > 200:
return n
else:
n = count(coins, value, n, j)
value = value - coins[j]
n = count(coins, value, n, j)
value = value - coins[j]
return n
def main():
start = default_timer()
@ -36,9 +39,10 @@ def main():
end = default_timer()
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__':
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,
# 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.
from timeit import default_timer
import numpy as np
from numpy import zeros
from timeit import default_timer
from projecteuler import is_pandigital
def main():
start = default_timer()
@ -26,14 +28,14 @@ def main():
# To get a 1 to 9 pandigital concatenation of the two factors and product,
# we need to multiply a 1 digit number times a 4 digit numbers (the biggest
# one digit number 9 times the biggest 3 digit number 999 multiplied give
# 8991 and the total digit count is 8, which is not enough), or a 2 digit
# 8991 and the total digit count is 8, which is not enough), or a 2 digit
# number times a 3 digit number (the smallest two different 3 digits number,
# 100 and 101, multiplied give 10100, and the total digit count is 11, which
# is too many). The outer loop starts at 2 because 1 times any number gives
# the same number, so its digit will be repeated and the result can't be
# pandigital. The nested loop starts from 1234 because it's the smallest
# the same number, so its digit will be repeated and the result can't be
# pandigital. The nested loop starts from 1234 because it's the smallest
# 4-digit number with no repeated digits, and it ends at 4987 because it's
# the biggest number without repeated digits that multiplied by 2 gives a
# the biggest number without repeated digits that multiplied by 2 gives a
# 4 digit number.
for i in range(2, 9):
for j in range(1234, 4987):
@ -80,9 +82,10 @@ def main():
end = default_timer()
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__':
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,
# 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.
from math import gcd
from timeit import default_timer
def main():
start = default_timer()
@ -25,7 +25,7 @@ def main():
# If the example is non-trivial, check if cancelling the digit that's equal
# in numerator and denominator gives the same fraction.
if i % 10 != 0 and j % 10 != 0 and\
i != j and i % 10 == j // 10:
i != j and i % 10 == j // 10:
n = i // 10
d = j % 10
@ -42,9 +42,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -7,10 +7,10 @@
# Note: as 1! = 1 and 2! = 2 are not sums they are not included.
from math import factorial
from timeit import default_timer
from numpy import ones
from timeit import default_timer
def main():
start = default_timer()
@ -41,9 +41,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -7,18 +7,23 @@
# How many circular primes are there below one million?
from timeit import default_timer
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 primes[n] == 0:
return False
# The primes below 10 are circular primes.
if primes[n] == 1 and n < 10:
return True
return True
tmp = n
count = 0
@ -32,7 +37,7 @@ def is_circular_prime(n):
count = count + 1
tmp = tmp // 10
for i in range(1, count):
for _ in range(1, count):
# Generate rotations and check if they're prime.
n = n % (10 ** (count - 1)) * 10 + n // (10 ** (count - 1))
@ -41,15 +46,10 @@ def is_circular_prime(n):
return True
def main():
start = default_timer()
global primes
N = 1000000
# Calculate all primes below one million, then check if they're circular.
primes = sieve(N)
count = 13
# Calculate all primes below one million, then check if they're circular.
@ -60,9 +60,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -7,8 +7,10 @@
# (Please note that the palindromic number, in either base, may not include leading zeros.)
from timeit import default_timer
from projecteuler import is_palindrome
def main():
start = default_timer()
@ -26,9 +28,10 @@ def main():
end = default_timer()
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__':
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,
# 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.
from timeit import default_timer
from projecteuler import is_prime
def is_tr_prime(n):
# One-digit numbers and non-prime numbers are
# not truncatable primes.
@ -40,6 +42,7 @@ def is_tr_prime(n):
# If it gets here, the number is truncatable prime.
return True
def main():
start = default_timer()
@ -57,9 +60,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -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?
from numpy import zeros
from timeit import default_timer
from projecteuler import is_pandigital
def main():
start = default_timer()
@ -57,9 +57,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -6,9 +6,10 @@
#
# For which value of p ≤ 1000, is the number of solutions maximised?
from timeit import default_timer
from numpy import zeros
from timeit import default_timer
def main():
start = default_timer()
@ -68,9 +69,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -10,9 +10,10 @@
#
# d_1 × d_10 × d_100 × d_1000 × d_10000 × d_100000 × d_1000000
from timeit import default_timer
from numpy import zeros
from timeit import default_timer
def main():
start = default_timer()
@ -66,9 +67,10 @@ def main():
end = default_timer()
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__':
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
# and is also prime.
@ -6,8 +6,10 @@
# What is the largest n-digit pandigital prime that exists?
from timeit import default_timer
from projecteuler import is_pandigital, is_prime
def main():
start = default_timer()
@ -18,18 +20,19 @@ def main():
# until we find a prime.
i = 7654321
while(i > 0):
while i > 0:
if is_pandigital(i, len(str(i))) and is_prime(i):
break
# Skipping the even numbers.
i = i - 2
end = default_timer()
print('Project Euler, Problem 41')
print('Answer: {}'.format(i))
print('Elapsed time: {:.9f} seconds'.format(end - start))
print(f'Answer: {i}')
print(f'Elapsed time: {end - start:.9f} seconds')
if __name__ == '__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:
#
@ -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,
# how many are triangle words?
import sys
from timeit import default_timer
def is_triang(n):
i = 1
j = 1
@ -24,18 +26,16 @@ def is_triang(n):
return False
def main():
start = default_timer()
try:
fp = open('words.txt', 'r')
except:
print('Error while opening file {}'.format('words.txt'))
exit(1)
words = list(fp.readline().replace('"', '').split(','))
fp.close()
with open('words.txt', 'r', encoding='utf-8') as fp:
words = list(fp.readline().replace('"', '').split(','))
except FileNotFoundError:
print('Error while opening file words.txt')
sys.exit(1)
count = 0
@ -53,9 +53,10 @@ def main():
end = default_timer()
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__':
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
# rather interesting sub-string divisibility property.
@ -16,9 +16,9 @@
# Find the sum of all 0 to 9 pandigital numbers with this property.
from itertools import permutations
from timeit import default_timer
# Function to check if the value has the desired property.
def has_property(n):
value = int(n[1]) * 100 + int(n[2]) * 10 + int(n[3])
@ -50,7 +50,7 @@ def has_property(n):
if value % 13 != 0:
return False
value = int(n[7]) * 100 + int(n[8]) * 10 + int(n[9])
if value % 17 != 0:
@ -58,6 +58,7 @@ def has_property(n):
return True
def main():
start = default_timer()
@ -74,9 +75,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -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;
# what is the value of D?
from math import sqrt
from timeit import default_timer
from projecteuler import is_pentagonal
def main():
start = default_timer()
@ -38,9 +38,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -10,11 +10,11 @@
#
# Find the next triangle number that is also pentagonal and hexagonal.
from math import sqrt
from timeit import default_timer
from projecteuler import is_pentagonal
def main():
start = default_timer()
@ -34,9 +34,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -14,11 +14,15 @@
# 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 projecteuler import sieve
def goldbach(n):
global primes
N = 10000
primes = sieve(N)
def goldbach(n):
# Check every prime smaller than n.
for i in range(3, n, 2):
if primes[i] == 1:
@ -43,12 +47,6 @@ def goldbach(n):
def main():
start = default_timer()
global primes
N = 10000
primes = sieve(N)
found = 0
i = 3
@ -64,9 +62,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -15,6 +15,7 @@
from timeit import default_timer
# Function using a modified sieve of Eratosthenes to count
# the distinct prime factors of each number.
def count_factors(n):
@ -29,6 +30,7 @@ def count_factors(n):
return factors
def main():
start = default_timer()
@ -53,9 +55,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -6,6 +6,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -19,9 +20,10 @@ def main():
end = default_timer()
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__':
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,
# 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?
from numpy import zeros
from timeit import default_timer
from projecteuler import sieve
def main():
start = default_timer()
@ -35,18 +35,20 @@ def main():
if i + 2 * j < N and primes[i+j] == 1 and primes[i+2*j] == 1 and\
''.join(sorted(str(i))) == ''.join(sorted(str(i+j))) and\
''.join(sorted(str(i))) == ''.join(sorted(str(i+2*j))):
found = 1
break
if(found):
found = 1
break
if found:
break
i = i + 2
end = default_timer()
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__':
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:
#
@ -11,8 +11,10 @@
# Which prime, below one-million, can be written as the sum of the most consecutive primes?
from timeit import default_timer
from projecteuler import sieve
def main():
start = default_timer()
@ -64,9 +66,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -10,8 +10,16 @@
# value family.
from timeit import default_timer
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):
count = 0
@ -22,9 +30,8 @@ def count_digit(n, d):
return count
def replace(n):
global primes
def replace(n):
n_string = list(str(n))
l = len(n_string)
max_ = 0
@ -60,35 +67,29 @@ def replace(n):
def main():
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.
i = 1001
while i < N:
# The family of numbers needs to have at least one of 0, 1 or 2 as
# repeated digits, otherwise we can't get a 8 number family (there
# The family of numbers needs to have at least one of 0, 1 or 2 as
# repeated digits, otherwise we can't get a 8 number family (there
# are only 7 other digits). Also, te number of repeated digits must
# be 3, otherwise at least 3 resulting numbers will be divisible by 3.
# So the smallest number of this family must have three 0s, three 1s or
# three 2s.
if count_digit(i, 0) >= 3 or count_digit(i, 1) >= 3 or\
count_digit(i, 2) >= 3:
if primes[i] == 1 and replace(i) == 8:
break
if primes[i] == 1 and replace(i) == 8:
break
i = i + 2
end = default_timer()
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__':
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.
from numpy import zeros
from timeit import default_timer
def main():
start = default_timer()
@ -20,15 +19,16 @@ def main():
''.join(sorted(str(i))) == ''.join(sorted(str(4*i))) and\
''.join(sorted(str(i))) == ''.join(sorted(str(5*i))) and\
''.join(sorted(str(i))) == ''.join(sorted(str(6*i))):
break
break
i = i + 1
end = default_timer()
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__':
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?
from timeit import default_timer
from scipy.special import comb
from timeit import default_timer
def main():
start = default_timer()
@ -32,9 +33,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -46,10 +46,11 @@
#
# How many hands does Player 1 win?
import sys
from enum import IntEnum
from timeit import default_timer
class Value(IntEnum):
Two = 1
Three = 2
@ -65,10 +66,11 @@ class Value(IntEnum):
King = 12
Ace = 13
class Card():
def __init__(self, *args, **kwargs):
super(Card, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.value = None
self.suit = None
@ -103,20 +105,22 @@ class Card():
self.suit = card[1]
class Hand():
def __init__(self, *args, **kwargs):
super(Hand, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.cards = list()
def sort(self):
self.cards.sort(key=lambda x: x.value)
class Game():
def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.hand1 = None
self.hand2 = None
@ -130,7 +134,8 @@ class Game():
self.hand1.cards[0].suit == self.hand1.cards[2].suit and\
self.hand1.cards[0].suit == self.hand1.cards[3].suit and\
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 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\
@ -138,7 +143,7 @@ class Game():
self.hand2.cards[0].suit == self.hand2.cards[2].suit and\
self.hand2.cards[0].suit == self.hand2.cards[3].suit and\
self.hand2.cards[0].suit == self.hand2.cards[4].suit:
return -1
return -1
straightflush1 = 0
straightflush2 = 0
@ -146,35 +151,35 @@ class Game():
# Check if player 1 has a straight flush.
if self.hand1.cards[0].suit == self.hand1.cards[1].suit and self.hand1.cards[0].suit == self.hand1.cards[2].suit and\
self.hand1.cards[0].suit == self.hand1.cards[3].suit and self.hand1.cards[0].suit == self.hand1.cards[4].suit:
value = self.hand1.cards[0].value
value = self.hand1.cards[0].value
straightflush1 = 1
straightflush1 = 1
for i in range(1, 5):
value = value + 1
for i in range(1, 5):
value = value + 1
if self.hand1.cards[i].value != value:
straightflush1 = 0
break
if self.hand1.cards[i].value != value:
straightflush1 = 0
break
# Check if player 2 has a straight flush.
if self.hand2.cards[0].suit == self.hand2.cards[1].suit and self.hand2.cards[0].suit == self.hand2.cards[2].suit and\
self.hand2.cards[0].suit == self.hand2.cards[3].suit and self.hand2.cards[0].suit == self.hand2.cards[4].suit:
value = self.hand2.cards[0].value
value = self.hand2.cards[0].value
straightflush2 = 1
straightflush2 = 1
for i in range(1, 5):
value = value + 1
for i in range(1, 5):
value = value + 1
if self.hand2.cards[i].value != value:
straightflush2 = 0
break
if self.hand2.cards[i].value != value:
straightflush2 = 0
break
# If player 1 has a straight flush and player 2 doesn't, player 1 wins
if straightflush1 and not straightflush2:
return 1
# If player 2 has a straight flush and player 1 doesn't, player 2 wins
if not straightflush1 and straightflush2:
return -1
@ -185,8 +190,8 @@ class Game():
if straightflush1 and straightflush2:
if self.hand1.cards[0].value > self.hand2.cards[0].value:
return 1
else:
return -1
return -1
four1 = 0
four2 = 0
@ -221,12 +226,12 @@ class Game():
# Check if player 1 has a full house.
if self.hand1.cards[0].value == self.hand1.cards[1].value and self.hand1.cards[3].value == self.hand1.cards[4].value and\
(self.hand1.cards[1].value == self.hand1.cards[2].value or self.hand1.cards[2].value == self.hand1.cards[3].value):
full1 = 1
full1 = 1
# Check if player 2 has a full house.
if self.hand2.cards[0].value == self.hand2.cards[1].value and self.hand2.cards[3].value == self.hand2.cards[4].value and\
(self.hand2.cards[1].value == self.hand2.cards[2].value or self.hand2.cards[2].value == self.hand2.cards[3].value):
full2 = 1
full2 = 1
# If player 1 has a full house and player 2 doesn't, player 1 wins.
if full1 and not full2:
@ -242,7 +247,8 @@ class Game():
if full1 and full2:
if self.hand1.cards[2].value > self.hand2.cards[2].value:
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
flush1 = 0
@ -251,12 +257,12 @@ class Game():
# Check if player 1 has a flush.
if self.hand1.cards[0].suit == self.hand1.cards[1].suit and self.hand1.cards[0].suit == self.hand1.cards[2].suit and\
self.hand1.cards[0].suit == self.hand1.cards[3].suit and self.hand1.cards[0].suit == self.hand1.cards[4].suit:
flush1 = 1
flush1 = 1
# Check if player 2 has a flush.
if self.hand2.cards[0].suit == self.hand2.cards[1].suit and self.hand2.cards[0].suit == self.hand2.cards[2].suit and\
self.hand2.cards[0].suit == self.hand2.cards[3].suit and self.hand2.cards[0].suit == self.hand2.cards[4].suit:
flush2 = 1
flush2 = 1
# If player 1 has a flush and player 2 doesn't, player 1 wins.
if flush1 and not flush2:
@ -304,13 +310,13 @@ class Game():
if (self.hand1.cards[0].value == self.hand1.cards[1].value and self.hand1.cards[0].value == self.hand1.cards[2].value) or\
(self.hand1.cards[1].value == self.hand1.cards[2].value and self.hand1.cards[1].value == self.hand1.cards[3].value) or\
(self.hand1.cards[2].value == self.hand1.cards[3].value and self.hand1.cards[2].value == self.hand1.cards[4].value):
three1 = 1
three1 = 1
# Check if player 2 has three of a kind.
if (self.hand2.cards[0].value == self.hand2.cards[1].value and self.hand2.cards[0].value == self.hand2.cards[2].value) or\
(self.hand2.cards[1].value == self.hand2.cards[2].value and self.hand2.cards[1].value == self.hand2.cards[3].value) or\
(self.hand2.cards[2].value == self.hand2.cards[3].value and self.hand2.cards[2].value == self.hand2.cards[4].value):
three2 = 1
three2 = 1
# If player 1 has three of a kind and player 2 doesn't, player 1 wins.
if three1 and not three2:
@ -323,7 +329,8 @@ class Game():
if three1 and three2:
if self.hand1.cards[2].value > self.hand2.cards[2].value:
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
twopairs1 = 0
@ -333,13 +340,13 @@ class Game():
if (self.hand1.cards[0].value == self.hand1.cards[1].value and self.hand1.cards[2].value == self.hand1.cards[3].value) or\
(self.hand1.cards[0].value == self.hand1.cards[1].value and self.hand1.cards[3].value == self.hand1.cards[4].value) or\
(self.hand1.cards[1].value == self.hand1.cards[2].value and self.hand1.cards[3].value == self.hand1.cards[4].value):
twopairs1 = 1
twopairs1 = 1
# Check if player 2 has two pairs.
if (self.hand2.cards[0].value == self.hand2.cards[1].value and self.hand2.cards[2].value == self.hand2.cards[3].value) or\
(self.hand2.cards[0].value == self.hand2.cards[1].value and self.hand2.cards[3].value == self.hand2.cards[4].value) or\
(self.hand2.cards[1].value == self.hand2.cards[2].value and self.hand2.cards[3].value == self.hand2.cards[4].value):
twopairs2 = 1
twopairs2 = 1
# If player 1 has two pairs and player 2 doesn't, player 1 wins.
if twopairs1 and not twopairs2:
@ -354,17 +361,21 @@ class Game():
if twopairs1 and twopairs2:
if self.hand1.cards[3].value > self.hand2.cards[3].value:
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
elif self.hand1.cards[1].value > self.hand2.cards[1].value:
if self.hand1.cards[1].value > self.hand2.cards[1].value:
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
for i in range(4, -1, -1):
if self.hand1.cards[i].value > self.hand2.cards[i].value:
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
pair1 = 0
@ -373,12 +384,12 @@ class Game():
# Check if player 1 has a pair of cards.
if self.hand1.cards[0].value == self.hand1.cards[1].value or self.hand1.cards[1].value == self.hand1.cards[2].value or\
self.hand1.cards[2].value == self.hand1.cards[3].value or self.hand1.cards[3].value == self.hand1.cards[4].value:
pair1 = 1
pair1 = 1
# Check if player 2 has a pair of cards.
if self.hand2.cards[0].value == self.hand2.cards[1].value or self.hand2.cards[1].value == self.hand2.cards[2].value or\
self.hand2.cards[2].value == self.hand2.cards[3].value or self.hand2.cards[3].value == self.hand2.cards[4].value:
pair2 = 1
pair2 = 1
# If player 1 has a pair of cards and player 2 doesn't, player 1 wins.
if pair1 and not pair2:
@ -427,22 +438,20 @@ class Game():
return 1
if self.hand1.cards[i].value < self.hand2.cards[i].value:
return -1
# If everything is equal, return 0
return 0
def main():
start = default_timer()
try:
fp = open('poker.txt', 'r')
except:
print('Error while opening file {}'.format('poker.txt'))
exit(1)
games = fp.readlines()
fp.close()
with open('poker.txt', 'r', encoding='utf-8') as fp:
games = fp.readlines()
except FileNotFoundError:
print('Error while opening file poker.txt')
sys.exit(1)
count = 0
@ -478,9 +487,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -24,13 +24,15 @@
# NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.
from timeit import default_timer
from projecteuler import is_palindrome
def is_lychrel(n):
tmp = n
# Run for 50 iterations
for i in range(50):
for _ in range(50):
reverse = 0
# Find the reverse of the given number
@ -50,6 +52,7 @@ def is_lychrel(n):
return True
def main():
start = default_timer()
@ -64,9 +67,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -7,6 +7,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -28,9 +29,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -18,6 +18,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -27,10 +28,10 @@ def main():
# If n/d is the current term of the expansion, the next term can be calculated as
# (n+2d)/(n+d).
for i in range(1, 1000):
for _ in range(1, 1000):
d2 = 2 * d
d = n + d
n = n + d2
n = n + d2
if len(str(n)) > len(str(d)):
count = count + 1
@ -38,9 +39,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -17,14 +17,16 @@
# 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 projecteuler import is_prime
def main():
start = default_timer()
# Starting with 1, the next four numbers in the diagonal are 3 (1+2), 5 (1+2+2), 7 (1+2+2+2)
# and 9 (1+2+2+2+2). Check which are prime, increment the counter every time a new prime is
# found, and divide by the number of elements of the diagonal, which are increase by 4 at
# and 9 (1+2+2+2+2). Check which are prime, increment the counter every time a new prime is
# found, and divide by the number of elements of the diagonal, which are increase by 4 at
# every cycle. The next four number added to the diagonal are 13 (9+4), 17 (9+4+4), 21 and 25.
# Then 25+6 etc., at every cycle the step is increased by 2. Continue until the ratio goes below 0.1.
i = 1
@ -55,16 +57,17 @@ def main():
step = step + 2
diag = diag + 4
l = l + 2
if ratio < 0.1:
break
end = default_timer()
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__':
main()

View File

@ -20,66 +20,70 @@
from timeit import default_timer
class EncryptedText():
def __init__(self, *args, **kwargs):
super(EncryptedText, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.text = None
self.len = 0
def read_text(self, filename):
try:
fp = open(filename, 'r')
except:
print('Error while opening file {}'.format(filename))
with open(filename, 'r', encoding='utf-8') as fp:
self.text = list(map(int, list(fp.readline().split(','))))
except FileNotFoundError:
print(f'Error while opening file {filename}')
return -1
self.text = list(map(int, list(fp.readline().split(','))))
self.len = len(self.text)
fp.close()
def decrypt(self):
found = 0
for c1 in range(ord('a'), ord('z')+1):
if found:
if found:
break
for c2 in range(ord('a'), ord('z')+1):
if found:
break
for c3 in range(ord('a'), ord('z')+1):
if found:
break
plain_text = [''] * self.len
for i in range(0, self.len-2, 3):
plain_text[i] = str(chr(self.text[i]^c1))
plain_text[i+1] = str(chr(self.text[i+1]^c2))
plain_text[i+2] = str(chr(self.text[i+2]^c3))
for c2 in range(ord('a'), ord('z')+1):
if found:
break
for c3 in range(ord('a'), ord('z')+1):
if found:
break
if i == self.len - 2:
plain_text[i] = str(chr(self.text[i]^c1))
plain_text[i+1] = str(chr(self.text[i+1]^c2))
plain_text = [''] * self.len
if i == self.len - 1:
plain_text[i] = str(chr(self.text[i]^c1))
for i in range(0, self.len-2, 3):
plain_text[i] = str(chr(self.text[i]^c1))
plain_text[i+1] = str(chr(self.text[i+1]^c2))
plain_text[i+2] = str(chr(self.text[i+2]^c3))
plain_text = ''.join(plain_text)
if i == self.len - 2:
plain_text[i] = str(chr(self.text[i]^c1))
plain_text[i+1] = str(chr(self.text[i+1]^c2))
if i == self.len - 1:
plain_text[i] = str(chr(self.text[i]^c1))
plain_text = ''.join(plain_text)
if 'the' in plain_text and 'be' in plain_text and 'to' in plain_text and 'of' in plain_text and\
'and' in plain_text and 'in' in plain_text and 'that' in plain_text and 'have' in plain_text:
found = 1
if 'the' in plain_text and 'be' in plain_text and 'to' in plain_text and 'of' in plain_text and\
'and' in plain_text and 'in' in plain_text and 'that' in plain_text and 'have' in plain_text:
found = 1
return plain_text
def main():
start = default_timer()
enc_text = EncryptedText()
if enc_text.read_text('cipher.txt') == -1:
exit(1)
sys.exit(1)
plain_text = enc_text.decrypt()
@ -91,9 +95,10 @@ def main():
end = default_timer()
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__':
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.
from timeit import default_timer
from projecteuler import sieve, is_prime
def main():
start = default_timer()
@ -29,7 +31,7 @@ def main():
p2 = p1 + 2
while p2 < N and not found:
# If p2 is not prime, or at least one of the possible concatenations of
# If p2 is not prime, or at least one of the possible concatenations of
# p1 and p2 is not prime, go to the next number.
if primes[p2] == 0 or not is_prime(int(str(p1)+str(p2))) or not is_prime(int(str(p2)+str(p1))):
p2 = p2 + 2
@ -42,8 +44,9 @@ def main():
# p1, p2 and p3 is not prime, got to the next number.
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))):
p3 = p3 + 2
continue
p3 = p3 + 2
continue
p4 = p3 + 2
@ -53,8 +56,9 @@ def main():
if primes[p4] == 0 or not is_prime(int(str(p1)+str(p4))) or not is_prime(int(str(p4)+str(p1))) 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))):
p4 = p4 + 2
continue
p4 = p4 + 2
continue
p5 = p4 + 2
@ -65,8 +69,9 @@ def main():
not is_prime(int(str(p2)+str(p5))) or not is_prime(int(str(p5)+str(p2))) 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))):
p5 = p5 + 2
continue
p5 = p5 + 2
continue
# If it gets here, the five values have been found.
n = p1 + p2 + p3 + p4 + p5
@ -83,9 +88,10 @@ def main():
end = default_timer()
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__':
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
# 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,
# hexagonal, heptagonal, and octagonal, is represented by a different number in the set.
from timeit import default_timer
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,
# 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
# backtracking and tries the next polygonal number.
def find_set(step):
global polygonal
global chain
global flags
global sum_
# 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 step == 0:
chain[step] = j
sum_ = sum_ + j
sum_ += j
# Recursively try to add other numbers to the chain. If a solution
# is found, return 1.
@ -58,42 +62,34 @@ def find_set(step):
# If a solution was not found, backtrack, subtracting the value of
# 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,
# 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:
chain[step] = j
sum_ = sum_ + j
sum_ += j
return 1
# For every other step, add the number to the chain if possible, then recursively
# try to add other numbers.
elif step < 5 and j // 100 == chain[step-1] % 100:
chain[step] = j
sum_ = sum_ + j
sum_ += + j
if find_set(step+1):
return 1
# If a solution was not found, backtrack.
sum_ = sum_ - j
sum_ -= j
# Remove the flag for the current polygonal type.
flags[i] = 0
return 0
def main():
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
n = 1
@ -172,9 +168,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -5,9 +5,10 @@
#
# Find the smallest cube for which exactly five permutations of its digits are cube.
from timeit import default_timer
from numpy import zeros
from timeit import default_timer
def main():
start = default_timer()
@ -45,9 +46,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -6,6 +6,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -30,9 +31,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -42,19 +42,18 @@
#
# 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 projecteuler import build_sqrt_cont_fraction
def is_square(n):
p = sqrt(n)
m = int(p)
if p == m:
return True
else:
return False
return bool(p == m)
def main():
start = default_timer()
@ -74,9 +73,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -31,6 +31,7 @@
from timeit import default_timer
def main():
start = default_timer()
@ -41,10 +42,10 @@ def main():
n1 = 8
n2 = 11
# For a continued fractions [a_0; a_1, a_2, ...], the numerator of the
# For a continued fractions [a_0; a_1, a_2, ...], the numerator of the
# next convergent N_n=a_n*N_(n-1)+N_(n-2). The first three values for e are
# 3, 8 and 11, the next ones are easily calculated, considering that a_n
# follows a simple pattern:
# follows a simple pattern:
# a_1=1, a_2=2, a_3=1
# a_4=1, a_5=4, a_6=1
# a_7=1, a_8=6, a_9=1
@ -70,9 +71,10 @@ def main():
end = default_timer()
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__':
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.
from math import sqrt
from timeit import default_timer
from projecteuler import pell_eq
def is_square(n):
p = sqrt(n)
m = int(p)
if p == m:
return True
else:
return False
return bool(p == m)
def main():
start = default_timer()
@ -52,9 +51,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -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.
# There is an efficient algorithm to solve it. ;o)
import sys
from timeit import default_timer
from projecteuler import find_max_path
def main():
start = default_timer()
triang = []
try:
fp = open('triangle.txt', 'r')
except:
print('Error while opening file {}'.format('triangle.txt'))
exit(1)
triang = list()
for line in fp:
triang.append(line.strip('\n').split())
fp.close()
with open('triangle.txt', 'r', encoding='utf-8') as fp:
for line in fp:
triang.append(line.strip('\n').split())
except FileNotFoundError:
print('Error while opening file triangle.txt')
sys.exit(1)
l = len(triang)
@ -45,9 +45,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -46,9 +46,9 @@
#
from itertools import permutations
from timeit import default_timer
# 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
# represent the internal ring.
@ -91,8 +91,9 @@ def eval_ring(ring, n):
return res
def list_to_int(l):
if l == None:
if l is None:
return 0
res = 0
@ -108,6 +109,7 @@ def list_to_int(l):
return res
def main():
start = default_timer()
@ -118,8 +120,8 @@ def main():
n = None
for ring in rings:
eval_ = eval_ring(ring, 5);
eval_ = eval_ring(ring, 5)
# Convert the list into an integer number.
n = list_to_int(eval_)
@ -129,9 +131,10 @@ def main():
end = default_timer()
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__':
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
# 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.
from timeit import default_timer
from projecteuler import is_prime
def main():
start = default_timer()
@ -47,9 +49,10 @@ def main():
end = default_timer()
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__':
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
# 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.
from numpy import zeros
from timeit import default_timer
from projecteuler import sieve, is_semiprime, phi_semiprime
def main():
start = default_timer()
@ -26,14 +26,14 @@ def main():
for i in range(2, N):
# When n is prime, phi(n)=(n-1), so to minimize n/phi(n) we should
# use n prime. But n-1 can't be a permutation of n. The second best
# use n prime. But n-1 can't be a permutation of n. The second best
# bet is to use semiprimes. For a semiprime n=p*q, phi(n)=(p-1)(q-1).
# So we check if a number is semiprime, if yes calculate phi, finally
# check if phi(n) is a permutation of n and update the minimum if it's
# smaller.
semi_p, a, b = is_semiprime(i, primes)
if semi_p == True:
if semi_p is True:
p = phi_semiprime(i, a, b)
if ''.join(sorted(str(p))) == ''.join(sorted(str(i))) and i / p < min_:
@ -43,9 +43,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -12,9 +12,9 @@
# of the fraction immediately to the left of 3/7.
from math import gcd
from timeit import default_timer
def main():
start = default_timer()
@ -46,9 +46,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -11,8 +11,10 @@
# How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000?
from timeit import default_timer
from projecteuler import sieve, phi
def main():
start = default_timer()
@ -21,7 +23,7 @@ def main():
count = 0
primes = sieve(N)
# For any denominator d, the number of reduced proper fractions is
# For any denominator d, the number of reduced proper fractions is
# the number of fractions n/d where gcd(n, d)=1, which is the definition
# of Euler's Totient Function phi. It's sufficient to calculate phi for each
# denominator and sum the value.
@ -31,9 +33,10 @@ def main():
end = default_timer()
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__':
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.
#
@ -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?
from math import gcd
from timeit import default_timer
def main():
start = default_timer()
@ -33,9 +33,10 @@ def main():
end = default_timer()
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__':
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:
#
@ -23,13 +23,14 @@
# How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?
from math import factorial
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
count = 0
finished = 0
@ -68,16 +69,10 @@ def len_chain(n):
return count
def main():
start = default_timer()
global N
global chains
N = 1000000
chains = [0] * N
count = 0
# Simple brute force approach, for every number calculate
@ -89,9 +84,10 @@ def main():
end = default_timer()
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__':
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,
# 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?
from math import gcd
from timeit import default_timer
def main():
start = default_timer()
@ -46,7 +46,7 @@ def main():
b = 2 * m * 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
i = 2
@ -54,7 +54,7 @@ def main():
tmpb = i * b
tmpc = i * c
while(tmpa + tmpb + tmpc <= N):
while tmpa + tmpb + tmpc <= N:
l[tmpa+tmpb+tmpc] = l[tmpa+tmpb+tmpc] + 1
i = i + 1
@ -71,9 +71,10 @@ def main():
end = default_timer()
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__':
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 projecteuler import partition_fn
def main():
start = default_timer()
@ -16,9 +29,10 @@ def main():
end = default_timer()
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__':
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?
from timeit import default_timer
from projecteuler import is_prime
primes = [0] * 100
# Function using a simple recursive brute force approach
# to find all the partitions.
def count(value, n, i, target):
global primes
for j in range(i, 100):
value = value + primes[j]
if value == target:
return n + 1
elif value > target:
if value > target:
return n
else:
n = count(value, n, j, target)
value = value - primes[j]
n = count(value, n, j, target)
value = value - primes[j]
return n
def main():
start = default_timer()
global primes
primes = [0] * 100
# Generate a list of the first 100 primes.
i = 0
j = 0
@ -64,9 +65,10 @@ def main():
end = default_timer()
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__':
main()

View File

@ -3,19 +3,21 @@
# Let p(n) represent the number of different ways in which n coins can be separated into piles.
# For example, five coins can be separated into piles in exactly seven different ways, so p(5)=7.
#
# OOOOO
# OOOO O
# OOO OO
# OOO O O
# OO OO O
# OO O O O
# OOOOO
# OOOO O
# OOO OO
# OOO O O
# OO OO O
# OO O O O
# O O O O O
#
# Find the least value of n for which p(n) is divisible by one million.
from timeit import default_timer
from projecteuler import partition_fn
def main():
start = default_timer()
@ -26,16 +28,17 @@ def main():
i = 0
# Using the partition function to calculate the number of partitions,
# giving the result modulo N.*/
# giving the result modulo N.*/
while partition_fn(i, partitions, N) != 0:
i = i + 1
end = default_timer()
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__':
main()

View File

@ -8,13 +8,14 @@
# 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.
import sys
from itertools import permutations
from timeit import default_timer
def check_passcode(passcode, len_, logins, n):
# 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
# incompatible with the current passcode is found.
for i in range(n):
k = 0
@ -30,28 +31,26 @@ def check_passcode(passcode, len_, logins, n):
return 1
def main():
start = default_timer()
try:
fp = open('keylog.txt', 'r')
except:
print('Error while opening file {}'.format('keylog.txt'))
exit(1)
logins = fp.readlines()
fp.close()
with open('keylog.txt', 'r', encoding='utf-8') as fp:
logins = fp.readlines()
except FileNotFoundError:
print('Error while opening file keylog.txt')
sys.exit(1)
digits = [0] * 10
passcode_digits = [0] * 10
for i in logins:
keylog = int(i)
# Check which digits are present in the login attempts.
while True:
digits[keylog%10] = digits[keylog%10] + 1
digits[keylog % 10] = digits[keylog % 10] + 1
keylog = keylog // 10
if keylog == 0:
@ -97,9 +96,10 @@ def main():
end = default_timer()
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__':
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 all the irrational square roots
from timeit import default_timer
from mpmath import sqrt, mp
from timeit import default_timer
def is_square(n):
p = sqrt(n)
m = int(p)
if p == m:
return True
else:
return False
return bool(p == m)
def main():
start = default_timer()
@ -43,9 +41,10 @@ def main():
end = default_timer()
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__':
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
# by only moving right and down.
import sys
from timeit import default_timer
def sum_paths(matrix, m, n):
for i in range(m-2, -1, -1):
matrix[m-1][i] = matrix[m-1][i] + matrix[m-1][i+1]
@ -27,21 +29,20 @@ def sum_paths(matrix, m, n):
matrix[i][j] = matrix[i][j] + matrix[i][j+1]
return matrix[0][0]
def main():
start = default_timer()
try:
fp = open('matrix.txt', 'r')
except:
print('Error while opening file {}'.format('matrix.txt'))
exit(1)
matrix = fp.readlines()
fp.close()
with open('matrix.txt', 'r', encoding='utf-8') as fp:
matrix = fp.readlines()
except FileNotFoundError:
print('Error while opening file matrix.txt')
sys.exit(1)
j = 0
for i in matrix:
matrix[j] = list(map(int, i.strip().split(',')))
j = j + 1
@ -51,9 +52,10 @@ def main():
end = default_timer()
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__':
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.
import sys
from timeit import default_timer
from numpy import zeros
from timeit import default_timer
from projecteuler import dijkstra
def main():
start = default_timer()
try:
fp = open('matrix.txt', 'r')
except:
print('Error while opening file {}'.format('matrix.txt'))
exit(1)
with open('matrix.txt', 'r', encoding='utf-8') as fp:
matrix = fp.readlines()
except FileNotFoundError:
print('Error while opening file matrix.txt')
sys.exit(1)
matrix = fp.readlines()
distances = zeros((80, 80), int)
j = 0
for i in matrix:
matrix[j] = list(map(int, i.strip().split(',')))
j = j + 1
@ -53,9 +57,10 @@ def main():
end = default_timer()
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__':
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,
# 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 timeit import default_timer
from projecteuler import dijkstra
def main():
start = default_timer()
try:
fp = open('matrix.txt', 'r')
except:
print('Error while opening file {}'.format('matrix.txt'))
exit(1)
with open('matrix.txt', 'r', encoding='utf-8') as fp:
matrix = fp.readlines()
except FileNotFoundError:
print('Error while opening file matrix.txt')
sys.exit(1)
matrix = fp.readlines()
distances = zeros((80, 80), int)
j = 0
@ -36,16 +39,17 @@ def main():
matrix[j] = list(map(int, i.strip().split(',')))
j = j + 1
dijkstra(matrix, distances, 80, 80, 1, 1)
dijkstra(matrix, distances, 80, 80, 1, 1)
dist = distances[79][79]
end = default_timer()
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__':
main()

View File

@ -1,3 +1,5 @@
#! /usr/bin/env python3
# The Fibonacci sequence is defined by the recurrence relation:
#
# 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.
#!/usr/bin/python
from mpmath import matrix, mp
import sys
from timeit import default_timer
from mpmath import matrix
from projecteuler import is_pandigital
sys.set_int_max_str_digits(70000)
def main():
start = default_timer()
@ -45,13 +51,14 @@ def main():
if is_pandigital(int(str(fib)[:9]), 9):
found = 1
end = default_timer()
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__':
main()

View File

@ -10,11 +10,12 @@
from timeit import default_timer
def main():
start = default_timer()
N = 10000000
N = 1000000000
count = 0
# Brute force approach, sum each number and their reverse and
@ -23,16 +24,17 @@ def main():
if i % 10 != 0:
s = str(i + int(''.join(reversed(str(i)))))
if not '0' in s and not '2' in s and not '4' in s and\
not '6' in s and not '8' in s:
if '0' not in s and '2' not in s and '4' not in s and\
'6' not in s and '8' not in s:
count = count + 1
end = default_timer()
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__':
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,
# where each “_” is a single digit.
from timeit import default_timer
def main():
start = default_timer()
@ -37,10 +38,10 @@ def main():
end = default_timer()
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__':
main()

View File

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

View File

@ -1,3 +1,6 @@
# 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.
# 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.