Description
stringlengths
18
161k
Code
stringlengths
15
300k
project euler problem 5 https projecteuler netproblem5 smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder what is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20 references https en wiktionary orgwikievenlydivisible returns the smallest positive number that is evenly divisible divisible with no remainder by all of the numbers from 1 to n solution10 2520 solution15 360360 solution22 232792560 solution3 4 6 solution0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solutionasd traceback most recent call last typeerror parameter n must be int or castable to int returns the smallest positive number that is evenly divisible divisible with no remainder by all of the numbers from 1 to n solution 10 2520 solution 15 360360 solution 22 232792560 solution 3 4 6 solution 0 traceback most recent call last valueerror parameter n must be greater than or equal to one solution 17 traceback most recent call last valueerror parameter n must be greater than or equal to one solution traceback most recent call last typeerror parameter n must be int or castable to int solution asd traceback most recent call last typeerror parameter n must be int or castable to int
def solution(n: int = 20) -> int: try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 0 while 1: i += n * (n - 1) nfound = 0 for j in range(2, n): if i % j != 0: nfound = 1 break if nfound == 0: if i == 0: i = 1 return i return None if __name__ == "__main__": print(f"{solution() = }")
project euler problem 5 https projecteuler netproblem5 smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder what is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20 references https en wiktionary orgwikievenlydivisible https en wikipedia orgwikieuclideanalgorithm https en wikipedia orgwikileastcommonmultiple least common multiple using the property that lcma b greatestcommondivisora b ab lcm3 15 15 lcm1 27 27 lcm13 27 351 lcm64 48 192 returns the smallest positive number that is evenly divisible divisible with no remainder by all of the numbers from 1 to n solution10 2520 solution15 360360 solution22 232792560 project euler problem 5 https projecteuler net problem 5 smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder what is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20 references https en wiktionary org wiki evenly_divisible https en wikipedia org wiki euclidean_algorithm https en wikipedia org wiki least_common_multiple least common multiple using the property that lcm a b greatest_common_divisor a b a b lcm 3 15 15 lcm 1 27 27 lcm 13 27 351 lcm 64 48 192 returns the smallest positive number that is evenly divisible divisible with no remainder by all of the numbers from 1 to n solution 10 2520 solution 15 360360 solution 22 232792560
from maths.greatest_common_divisor import greatest_common_divisor def lcm(x: int, y: int) -> int: return (x * y) // greatest_common_divisor(x, y) def solution(n: int = 20) -> int: g = 1 for i in range(1, n + 1): g = lcm(g, i) return g if __name__ == "__main__": print(f"{solution() = }")
project euler problem 6 https projecteuler netproblem6 sum square difference the sum of the squares of the first ten natural numbers is 12 22 102 385 the square of the sum of the first ten natural numbers is 1 2 102 552 3025 hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 2640 find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum returns the difference between the sum of the squares of the first n natural numbers and the square of the sum solution10 2640 solution15 13160 solution20 41230 solution50 1582700 returns the difference between the sum of the squares of the first n natural numbers and the square of the sum solution 10 2640 solution 15 13160 solution 20 41230 solution 50 1582700
def solution(n: int = 100) -> int: sum_of_squares = 0 sum_of_ints = 0 for i in range(1, n + 1): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(f"{solution() = }")
project euler problem 6 https projecteuler netproblem6 sum square difference the sum of the squares of the first ten natural numbers is 12 22 102 385 the square of the sum of the first ten natural numbers is 1 2 102 552 3025 hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 2640 find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum returns the difference between the sum of the squares of the first n natural numbers and the square of the sum solution10 2640 solution15 13160 solution20 41230 solution50 1582700 returns the difference between the sum of the squares of the first n natural numbers and the square of the sum solution 10 2640 solution 15 13160 solution 20 41230 solution 50 1582700
def solution(n: int = 100) -> int: sum_cubes = (n * (n + 1) // 2) ** 2 sum_squares = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
project euler problem 6 https projecteuler netproblem6 sum square difference the sum of the squares of the first ten natural numbers is 12 22 102 385 the square of the sum of the first ten natural numbers is 1 2 102 552 3025 hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 2640 find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum returns the difference between the sum of the squares of the first n natural numbers and the square of the sum solution10 2640 solution15 13160 solution20 41230 solution50 1582700 returns the difference between the sum of the squares of the first n natural numbers and the square of the sum solution 10 2640 solution 15 13160 solution 20 41230 solution 50 1582700
import math def solution(n: int = 100) -> int: sum_of_squares = sum(i * i for i in range(1, n + 1)) square_of_sum = int(math.pow(sum(range(1, n + 1)), 2)) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"{solution() = }")
project euler problem 6 https projecteuler netproblem6 sum square difference the sum of the squares of the first ten natural numbers is 12 22 102 385 the square of the sum of the first ten natural numbers is 1 2 102 552 3025 hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 2640 find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum returns the difference between the sum of the squares of the first n natural numbers and the square of the sum solution10 2640 solution15 13160 solution20 41230 solution50 1582700 returns the difference between the sum of the squares of the first n natural numbers and the square of the sum solution 10 2640 solution 15 13160 solution 20 41230 solution 50 1582700
def solution(n: int = 100) -> int: sum_of_squares = n * (n + 1) * (2 * n + 1) / 6 square_of_sum = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 7 https projecteuler netproblem7 10001st prime by listing the first six prime numbers 2 3 5 7 11 and 13 we can see that the 6th prime is 13 what is the 10001st prime number references https en wikipedia orgwikiprimenumber checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number i e if the result is true then the number is indeed prime else it is not isprime2 true isprime3 true isprime27 false isprime2999 true isprime0 false isprime1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the nth prime number solution6 13 solution1 2 solution3 5 solution20 71 solution50 229 solution100 541 checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number i e if the result is true then the number is indeed prime else it is not is_prime 2 true is_prime 3 true is_prime 27 false is_prime 2999 true is_prime 0 false is_prime 1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the n th prime number solution 6 13 solution 1 2 solution 3 5 solution 20 71 solution 50 229 solution 100 541
from math import sqrt def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(nth: int = 10001) -> int: count = 0 number = 1 while count != nth and number < 3: number += 1 if is_prime(number): count += 1 while count != nth: number += 2 if is_prime(number): count += 1 return number if __name__ == "__main__": print(f"{solution() = }")
project euler problem 7 https projecteuler netproblem7 10001st prime by listing the first six prime numbers 2 3 5 7 11 and 13 we can see that the 6th prime is 13 what is the 10001st prime number references https en wikipedia orgwikiprimenumber checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number i e if the result is true then the number is indeed prime else it is not isprime2 true isprime3 true isprime27 false isprime2999 true isprime0 false isprime1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the nth prime number solution6 13 solution1 2 solution3 5 solution20 71 solution50 229 solution100 541 solution3 4 5 solution0 traceback most recent call last valueerror parameter nth must be greater than or equal to one solution17 traceback most recent call last valueerror parameter nth must be greater than or equal to one solution traceback most recent call last typeerror parameter nth must be int or castable to int solutionasd traceback most recent call last typeerror parameter nth must be int or castable to int checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number i e if the result is true then the number is indeed prime else it is not is_prime 2 true is_prime 3 true is_prime 27 false is_prime 2999 true is_prime 0 false is_prime 1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the n th prime number solution 6 13 solution 1 2 solution 3 5 solution 20 71 solution 50 229 solution 100 541 solution 3 4 5 solution 0 traceback most recent call last valueerror parameter nth must be greater than or equal to one solution 17 traceback most recent call last valueerror parameter nth must be greater than or equal to one solution traceback most recent call last typeerror parameter nth must be int or castable to int solution asd traceback most recent call last typeerror parameter nth must be int or castable to int
import math def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(nth: int = 10001) -> int: try: nth = int(nth) except (TypeError, ValueError): raise TypeError("Parameter nth must be int or castable to int.") from None if nth <= 0: raise ValueError("Parameter nth must be greater than or equal to one.") primes: list[int] = [] num = 2 while len(primes) < nth: if is_prime(num): primes.append(num) num += 1 else: num += 1 return primes[len(primes) - 1] if __name__ == "__main__": print(f"{solution() = }")
project euler problem 7 https projecteuler netproblem7 10001st prime by listing the first six prime numbers 2 3 5 7 11 and 13 we can see that the 6th prime is 13 what is the 10001st prime number references https en wikipedia orgwikiprimenumber checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number i e if the result is true then the number is indeed prime else it is not isprime2 true isprime3 true isprime27 false isprime2999 true isprime0 false isprime1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 generate a sequence of prime numbers returns the nth prime number solution6 13 solution1 2 solution3 5 solution20 71 solution50 229 solution100 541 checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number i e if the result is true then the number is indeed prime else it is not is_prime 2 true is_prime 3 true is_prime 27 false is_prime 2999 true is_prime 0 false is_prime 1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 generate a sequence of prime numbers returns the n th prime number solution 6 13 solution 1 2 solution 3 5 solution 20 71 solution 50 229 solution 100 541
import itertools import math def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def prime_generator(): num = 2 while True: if is_prime(num): yield num num += 1 def solution(nth: int = 10001) -> int: return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 8 https projecteuler netproblem8 largest product in a series the four adjacent digits in the 1000digit number that have the greatest product are 9 9 8 9 5832 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 find the thirteen adjacent digits in the 1000digit number that have the greatest product what is the value of this product find the thirteen adjacent digits in the 1000digit number n that have the greatest product and returns it solution13978431290823798458352374 609638400 solution13978431295823798458352374 2612736000 solution1397843129582379841238352374 209018880 find the thirteen adjacent digits in the 1000 digit number n that have the greatest product and returns it solution 13978431290823798458352374 609638400 solution 13978431295823798458352374 2612736000 solution 1397843129582379841238352374 209018880
import sys N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) if product > largest_product: largest_product = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
project euler problem 8 https projecteuler netproblem8 largest product in a series the four adjacent digits in the 1000digit number that have the greatest product are 9 9 8 9 5832 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 find the thirteen adjacent digits in the 1000digit number that have the greatest product what is the value of this product find the thirteen adjacent digits in the 1000digit number n that have the greatest product and returns it solution13978431290823798458352374 609638400 solution13978431295823798458352374 2612736000 solution1397843129582379841238352374 209018880 mypy cannot properly interpret reduce find the thirteen adjacent digits in the 1000 digit number n that have the greatest product and returns it solution 13978431290823798458352374 609638400 solution 13978431295823798458352374 2612736000 solution 1397843129582379841238352374 209018880 mypy cannot properly interpret reduce
from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: return max( int(reduce(lambda x, y: str(int(x) * int(y)), n[i : i + 13])) for i in range(len(n) - 12) ) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 8 https projecteuler netproblem8 largest product in a series the four adjacent digits in the 1000digit number that have the greatest product are 9 9 8 9 5832 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 find the thirteen adjacent digits in the 1000digit number that have the greatest product what is the value of this product returns product of digits in given string n streval987654321 362880 streval22222222 256 find the thirteen adjacent digits in the 1000digit number n that have the greatest product and returns it returns product of digits in given string n str_eval 987654321 362880 str_eval 22222222 256 find the thirteen adjacent digits in the 1000 digit number n that have the greatest product and returns it
import sys N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def str_eval(s: str) -> int: product = 1 for digit in s: product *= int(digit) return product def solution(n: str = N) -> int: largest_product = -sys.maxsize - 1 substr = n[:13] cur_index = 13 while cur_index < len(n) - 13: if int(n[cur_index]) >= int(substr[0]): substr = substr[1:] + n[cur_index] cur_index += 1 else: largest_product = max(largest_product, str_eval(substr)) substr = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f"{solution() = }")
project euler problem 9 https projecteuler netproblem9 special pythagorean triplet a pythagorean triplet is a set of three natural numbers a b c for which a2 b2 c2 for example 32 42 9 16 25 52 there exists exactly one pythagorean triplet for which a b c 1000 find the product abc references https en wikipedia orgwikipythagoreantriple returns the product of a b c which are pythagorean triplet that satisfies the following 1 a b c 2 a2 b2 c2 3 a b c 1000 solution 31875000 returns the product of a b c which are pythagorean triplet that satisfies the following 1 a b c 2 a2 b2 c2 3 a b c 1000 solutionfast 31875000 benchmark code comparing two different version function returns the product of a b c which are pythagorean triplet that satisfies the following 1 a b c 2 a 2 b 2 c 2 3 a b c 1000 solution 31875000 returns the product of a b c which are pythagorean triplet that satisfies the following 1 a b c 2 a 2 b 2 c 2 3 a b c 1000 solution_fast 31875000 benchmark code comparing two different version function
def solution() -> int: for a in range(300): for b in range(a + 1, 400): for c in range(b + 1, 500): if (a + b + c) == 1000 and (a**2) + (b**2) == (c**2): return a * b * c return -1 def solution_fast() -> int: for a in range(300): for b in range(400): c = 1000 - a - b if a < b < c and (a**2) + (b**2) == (c**2): return a * b * c return -1 def benchmark() -> None: import timeit print( timeit.timeit("solution()", setup="from __main__ import solution", number=1000) ) print( timeit.timeit( "solution_fast()", setup="from __main__ import solution_fast", number=1000 ) ) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 9 https projecteuler netproblem9 special pythagorean triplet a pythagorean triplet is a set of three natural numbers a b c for which a2 b2 c2 for example 32 42 9 16 25 52 there exists exactly one pythagorean triplet for which a b c 1000 find the product abc references https en wikipedia orgwikipythagoreantriple return the product of a b c which are pythagorean triplet that satisfies the following 1 a b c 2 a2 b2 c2 3 a b c n solution36 1620 solution126 66780 solving the two equations a2b2c2 and abcn eliminating c return the product of a b c which are pythagorean triplet that satisfies the following 1 a b c 2 a 2 b 2 c 2 3 a b c n solution 36 1620 solution 126 66780 solving the two equations a 2 b 2 c 2 and a b c n eliminating c
def solution(n: int = 1000) -> int: product = -1 candidate = 0 for a in range(1, n // 3): b = (n * n - 2 * a * n) // (2 * n - 2 * a) c = n - a - b if c * c == (a * a + b * b): candidate = a * b * c if candidate >= product: product = candidate return product if __name__ == "__main__": print(f"{solution() = }")
project euler problem 9 https projecteuler netproblem9 special pythagorean triplet a pythagorean triplet is a set of three natural numbers a b c for which a2 b2 c2 for example 32 42 9 16 25 52 there exists exactly one pythagorean triplet for which a b c 1000 find the product abc references https en wikipedia orgwikipythagoreantriple returns the product of a b c which are pythagorean triplet that satisfies the following 1 a2 b2 c2 2 a b c 1000 solution 31875000 returns the product of a b c which are pythagorean triplet that satisfies the following 1 a 2 b 2 c 2 2 a b c 1000 solution 31875000
def solution() -> int: return next( iter( [ a * b * (1000 - a - b) for a in range(1, 999) for b in range(a, 999) if (a * a + b * b == (1000 - a - b) ** 2) ] ) ) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 10 https projecteuler netproblem10 summation of primes the sum of the primes below 10 is 2 3 5 7 17 find the sum of all the primes below two million references https en wikipedia orgwikiprimenumber checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number num i e if the result is true then the number is indeed prime else it is not isprime2 true isprime3 true isprime27 false isprime2999 true isprime0 false isprime1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the sum of all the primes below n solution1000 76127 solution5000 1548136 solution10000 5736396 solution7 10 checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number num i e if the result is true then the number is indeed prime else it is not is_prime 2 true is_prime 3 true is_prime 27 false is_prime 2999 true is_prime 0 false is_prime 1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the sum of all the primes below n solution 1000 76127 solution 5000 1548136 solution 10000 5736396 solution 7 10
import math def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(n: int = 2000000) -> int: return sum(num for num in range(3, n, 2) if is_prime(num)) + 2 if n > 2 else 0 if __name__ == "__main__": print(f"{solution() = }")
project euler problem 10 https projecteuler netproblem10 summation of primes the sum of the primes below 10 is 2 3 5 7 17 find the sum of all the primes below two million references https en wikipedia orgwikiprimenumber checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number num i e if the result is true then the number is indeed prime else it is not isprime2 true isprime3 true isprime27 false isprime2999 true isprime0 false isprime1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 generate a list sequence of prime numbers returns the sum of all the primes below n solution1000 76127 solution5000 1548136 solution10000 5736396 solution7 10 checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number num i e if the result is true then the number is indeed prime else it is not is_prime 2 true is_prime 3 true is_prime 27 false is_prime 2999 true is_prime 0 false is_prime 1 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 generate a list sequence of prime numbers returns the sum of all the primes below n solution 1000 76127 solution 5000 1548136 solution 10000 5736396 solution 7 10
import math from collections.abc import Iterator from itertools import takewhile def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def prime_generator() -> Iterator[int]: num = 2 while True: if is_prime(num): yield num num += 1 def solution(n: int = 2000000) -> int: return sum(takewhile(lambda x: x < n, prime_generator())) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 10 https projecteuler netproblem10 summation of primes the sum of the primes below 10 is 2 3 5 7 17 find the sum of all the primes below two million references https en wikipedia orgwikiprimenumber https en wikipedia orgwikisieveoferatosthenes returns the sum of all the primes below n using sieve of eratosthenes the sieve of eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million only for positive numbers solution1000 76127 solution5000 1548136 solution10000 5736396 solution7 10 solution7 1 doctest ellipsis traceback most recent call last typeerror float object cannot be interpreted as an integer solution7 doctest ellipsis traceback most recent call last indexerror list assignment index out of range solutionseven doctest ellipsis traceback most recent call last typeerror can only concatenate str not int to str returns the sum of all the primes below n using sieve of eratosthenes the sieve of eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million only for positive numbers solution 1000 76127 solution 5000 1548136 solution 10000 5736396 solution 7 10 solution 7 1 doctest ellipsis traceback most recent call last typeerror float object cannot be interpreted as an integer solution 7 doctest ellipsis traceback most recent call last indexerror list assignment index out of range solution seven doctest ellipsis traceback most recent call last typeerror can only concatenate str not int to str
def solution(n: int = 2000000) -> int: primality_list = [0 for i in range(n + 1)] primality_list[0] = 1 primality_list[1] = 1 for i in range(2, int(n**0.5) + 1): if primality_list[i] == 0: for j in range(i * i, n + 1, i): primality_list[j] = 1 sum_of_primes = 0 for i in range(n): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"{solution() = }")
what is the greatest product of four adjacent numbers horizontally vertically or diagonally in this 20x20 array 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 check vertically horizontally diagonally at the same time only works for nxn grid lefttoright diagonal product righttoleft diagonal product returns the greatest product of four adjacent numbers horizontally vertically or diagonally solution 70600674 check vertically horizontally diagonally at the same time only works for nxn grid left to right diagonal product right to left diagonal product returns the greatest product of four adjacent numbers horizontally vertically or diagonally solution 70600674
import os def largest_product(grid): n_columns = len(grid[0]) n_rows = len(grid) largest = 0 lr_diag_product = 0 rl_diag_product = 0 for i in range(n_columns): for j in range(n_rows - 3): vert_product = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] horz_product = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] if i < n_columns - 3: lr_diag_product = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) if i > 2: rl_diag_product = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) max_product = max( vert_product, horz_product, lr_diag_product, rl_diag_product ) if max_product > largest: largest = max_product return largest def solution(): grid = [] with open(os.path.dirname(__file__) + "/grid.txt") as file: for line in file: grid.append(line.strip("\n").split(" ")) grid = [[int(i) for i in grid[j]] for j in range(len(grid))] return largest_product(grid) if __name__ == "__main__": print(solution())
what is the greatest product of four adjacent numbers horizontally vertically or diagonally in this 20x20 array 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 returns the greatest product of four adjacent numbers horizontally vertically or diagonally solution 70600674 right down diagonal 1 diagonal 2 returns the greatest product of four adjacent numbers horizontally vertically or diagonally solution 70600674 noqa e741 right down diagonal 1 diagonal 2
import os def solution(): with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] for _ in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp for i in range(17): for j in range(17): temp = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: maximum = temp for i in range(17): for j in range(3, 20): temp = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
highly divisible triangular numbers problem 12 the sequence of triangle numbers is generated by adding the natural numbers so the 7th triangle number would be 1 2 3 4 5 6 7 28 the first ten terms would be 1 3 6 10 15 21 28 36 45 55 let us list the factors of the first seven triangle numbers 1 1 3 1 3 6 1 2 3 6 10 1 2 5 10 15 1 3 5 15 21 1 3 7 21 28 1 2 4 7 14 28 we can see that 28 is the first triangle number to have over five divisors what is the value of the first triangle number to have over five hundred divisors returns the value of the first triangle number to have over five hundred divisors solution 76576500 returns the value of the first triangle number to have over five hundred divisors solution 76576500
def count_divisors(n): n_divisors = 1 i = 2 while i * i <= n: multiplicity = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def solution(): t_num = 1 i = 1 while True: i += 1 t_num += i if count_divisors(t_num) > 500: break return t_num if __name__ == "__main__": print(solution())
highly divisible triangular numbers problem 12 the sequence of triangle numbers is generated by adding the natural numbers so the 7th triangle number would be 1 2 3 4 5 6 7 28 the first ten terms would be 1 3 6 10 15 21 28 36 45 55 let us list the factors of the first seven triangle numbers 1 1 3 1 3 6 1 2 3 6 10 1 2 5 10 15 1 3 5 15 21 1 3 7 21 28 1 2 4 7 14 28 we can see that 28 is the first triangle number to have over five divisors what is the value of the first triangle number to have over five hundred divisors returns the value of the first triangle number to have over five hundred divisors solution 76576500 returns the value of the first triangle number to have over five hundred divisors solution 76576500
def triangle_number_generator(): for n in range(1, 1000000): yield n * (n + 1) // 2 def count_divisors(n): divisors_count = 1 i = 2 while i * i <= n: multiplicity = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def solution(): return next(i for i in triangle_number_generator() if count_divisors(i) > 500) if __name__ == "__main__": print(solution())
problem 13 https projecteuler netproblem13 problem statement work out the first ten digits of the sum of the following onehundred 50digit numbers returns the first ten digits of the sum of the array elements from the file num txt solution 5537376230 returns the first ten digits of the sum of the array elements from the file num txt solution 5537376230
import os def solution(): file_path = os.path.join(os.path.dirname(__file__), "num.txt") with open(file_path) as file_hand: return str(sum(int(line) for line in file_hand))[:10] if __name__ == "__main__": print(solution())
problem 14 https projecteuler netproblem14 problem statement the following iterative sequence is defined for the set of positive integers n n2 n is even n 3n 1 n is odd using the rule above and starting with 13 we generate the following sequence 13 40 20 10 5 16 8 4 2 1 it can be seen that this sequence starting at 13 and finishing at 1 contains 10 terms although it has not been proved yet collatz problem it is thought that all starting numbers finish at 1 which starting number under one million produces the longest chain returns the number under n that generates the longest sequence using the formula n n2 n is even n 3n 1 n is odd solution1000000 837799 solution200 171 solution5000 3711 solution15000 13255 returns the number under n that generates the longest sequence using the formula n n 2 n is even n 3n 1 n is odd solution 1000000 837799 solution 200 171 solution 5000 3711 solution 15000 13255
def solution(n: int = 1000000) -> int: largest_number = 1 pre_counter = 1 counters = {1: 1} for input1 in range(2, n): counter = 0 number = input1 while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: number = (3 * number) + 1 counter += 1 if input1 not in counters: counters[input1] = counter if counter > pre_counter: largest_number = input1 pre_counter = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
problem 14 https projecteuler netproblem14 collatz conjecture start with any positive integer n next term obtained from the previous term as follows if the previous term is even the next term is one half the previous term if the previous term is odd the next term is 3 times the previous term plus 1 the conjecture states the sequence will always reach 1 regardless of starting n problem statement the following iterative sequence is defined for the set of positive integers n n2 n is even n 3n 1 n is odd using the rule above and starting with 13 we generate the following sequence 13 40 20 10 5 16 8 4 2 1 it can be seen that this sequence starting at 13 and finishing at 1 contains 10 terms although it has not been proved yet collatz problem it is thought that all starting numbers finish at 1 which starting number under one million produces the longest chain returns the collatz sequence length for n if n in collatzsequencelengths return collatzsequencelengthsn nextn n 2 if n 2 0 else 3 n 1 sequencelength collatzsequencelengthnextn 1 collatzsequencelengthsn sequencelength return sequencelength def solutionn int 1000000 int result maxcollatzsequencelengthi i for i in range1 n return result1 if name main printsolutionintinput strip returns the collatz sequence length for n returns the number under n that generates the longest collatz sequence solution 1000000 837799 solution 200 171 solution 5000 3711 solution 15000 13255
from __future__ import annotations COLLATZ_SEQUENCE_LENGTHS = {1: 1} def collatz_sequence_length(n: int) -> int: if n in COLLATZ_SEQUENCE_LENGTHS: return COLLATZ_SEQUENCE_LENGTHS[n] next_n = n // 2 if n % 2 == 0 else 3 * n + 1 sequence_length = collatz_sequence_length(next_n) + 1 COLLATZ_SEQUENCE_LENGTHS[n] = sequence_length return sequence_length def solution(n: int = 1000000) -> int: result = max((collatz_sequence_length(i), i) for i in range(1, n)) return result[1] if __name__ == "__main__": print(solution(int(input().strip())))
problem 15 https projecteuler netproblem15 starting in the top left corner of a 22 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 2020 grid returns the number of paths possible in a n x n grid starting at top left corner going to bottom right corner and being able to move right and down only solution25 126410606437752 solution23 8233430727600 solution20 137846528820 solution15 155117520 solution1 2 2 3 returns the number of paths possible in a n x n grid starting at top left corner going to bottom right corner and being able to move right and down only solution 25 126410606437752 solution 23 8233430727600 solution 20 137846528820 solution 15 155117520 solution 1 2 middle entry of odd rows starting at row 3 is the solution for n 1 2 3
from math import factorial def solution(n: int = 20) -> int: n = 2 * n k = n // 2 return int(factorial(n) / (factorial(k) * factorial(n - k))) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: n = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number.")
problem 16 https projecteuler netproblem16 215 32768 and the sum of its digits is 3 2 7 6 8 26 what is the sum of the digits of the number 21000 returns the sum of the digits of the number 2power solution1000 1366 solution50 76 solution20 31 solution15 26 returns the sum of the digits of the number 2 power solution 1000 1366 solution 50 76 solution 20 31 solution 15 26
def solution(power: int = 1000) -> int: num = 2**power string_num = str(num) list_num = list(string_num) sum_of_num = 0 for i in list_num: sum_of_num += int(i) return sum_of_num if __name__ == "__main__": power = int(input("Enter the power of 2: ").strip()) print("2 ^ ", power, " = ", 2**power) result = solution(power) print("Sum of the digits is: ", result)
problem 16 https projecteuler netproblem16 215 32768 and the sum of its digits is 3 2 7 6 8 26 what is the sum of the digits of the number 21000 returns the sum of the digits of the number 2power solution1000 1366 solution50 76 solution20 31 solution15 26 returns the sum of the digits of the number 2 power solution 1000 1366 solution 50 76 solution 20 31 solution 15 26
def solution(power: int = 1000) -> int: n = 2**power r = 0 while n: r, n = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
number letter counts problem 17 https projecteuler netproblem17 if the numbers 1 to 5 are written out in words one two three four five then there are 3 3 5 4 4 19 letters used in total if all the numbers from 1 to 1000 one thousand inclusive were written out in words how many letters would be used note do not count spaces or hyphens for example 342 three hundred and fortytwo contains 23 letters and 115 one hundred and fifteen contains 20 letters the use of and when writing out numbers is in compliance withbritish usage returns the number of letters used to write all numbers from 1 to n where n is lower or equals to 1000 solution1000 21124 solution5 19 number of letters in zero one two nineteen 0 for zero since it s never said aloud number of letters in twenty thirty ninety 0 for numbers less than 20 due to inconsistency in teens add number of letters for n hundred add number of letters for and if number is not multiple of 100 add number of letters for one two three nineteen could be combined with below if not for inconsistency in teens add number of letters for twenty twenty one ninety nine returns the number of letters used to write all numbers from 1 to n where n is lower or equals to 1000 solution 1000 21124 solution 5 19 number of letters in zero one two nineteen 0 for zero since it s never said aloud number of letters in twenty thirty ninety 0 for numbers less than 20 due to inconsistency in teens add number of letters for n hundred add number of letters for and if number is not multiple of 100 add number of letters for one two three nineteen could be combined with below if not for inconsistency in teens add number of letters for twenty twenty one ninety nine
def solution(n: int = 1000) -> int: ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: count += ones_counts[i // 100] + 7 if i % 100 != 0: count += 3 if 0 < i % 100 < 20: count += ones_counts[i % 100] else: count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
by starting at the top of the triangle below and moving to adjacent numbers on the row below the maximum total from top to bottom is 23 3 7 4 2 4 6 8 5 9 3 that is 3 7 4 9 23 find the maximum total from top to bottom of the triangle below 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 finds the maximum total in a triangle as described by the problem statement above solution 1074 finds the maximum total in a triangle as described by the problem statement above solution 1074
import os def solution(): script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") with open(triangle) as f: triangle = f.readlines() a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle] for i in range(1, len(a)): for j in range(len(a[i])): number1 = a[i - 1][j] if j != len(a[i - 1]) else 0 number2 = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(number1, number2) return max(a[-1]) if __name__ == "__main__": print(solution())
counting sundays problem 19 you are given the following information but you may prefer to do some research for yourself 1 jan 1900 was a monday thirty days has september april june and november all the rest have thirtyone saving february alone which has twentyeight rain or shine and on leap years twentynine a leap year occurs on any year evenly divisible by 4 but not on a century unless it is divisible by 400 how many sundays fell on the first of the month during the twentieth century 1 jan 1901 to 31 dec 2000 returns the number of mondays that fall on the first of the month during the twentieth century 1 jan 1901 to 31 dec 2000 solution 171 returns the number of mondays that fall on the first of the month during the twentieth century 1 jan 1901 to 31 dec 2000 solution 171
def solution(): days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day = 6 month = 1 year = 1901 sundays = 0 while year < 2001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 day = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 day = day - 29 else: if day > days_per_month[month - 1]: month += 1 day = day - days_per_month[month - 2] if month > 12: year += 1 month = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
problem 20 https projecteuler netproblem20 n means n n 1 3 2 1 for example 10 10 9 3 2 1 3628800 and the sum of the digits in the number 10 is 3 6 2 8 8 0 0 27 find the sum of the digits in the number 100 find the factorial of a given number n fact 1 for i in range1 num 1 fact i return fact def splitandaddnumber int int returns the sum of the digits in the factorial of num solution100 648 solution50 216 solution10 27 solution5 3 solution3 6 solution2 2 solution1 1 find the factorial of a given number n split number digits and add them removing the last_digit from the given number returns the sum of the digits in the factorial of num solution 100 648 solution 50 216 solution 10 27 solution 5 3 solution 3 6 solution 2 2 solution 1 1
def factorial(num: int) -> int: fact = 1 for i in range(1, num + 1): fact *= i return fact def split_and_add(number: int) -> int: sum_of_digits = 0 while number > 0: last_digit = number % 10 sum_of_digits += last_digit number = number // 10 return sum_of_digits def solution(num: int = 100) -> int: nfact = factorial(num) result = split_and_add(nfact) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
problem 20 https projecteuler netproblem20 n means n n 1 3 2 1 for example 10 10 9 3 2 1 3628800 and the sum of the digits in the number 10 is 3 6 2 8 8 0 0 27 find the sum of the digits in the number 100 returns the sum of the digits in the factorial of num solution100 648 solution50 216 solution10 27 solution5 3 solution3 6 solution2 2 solution1 1 returns the sum of the digits in the factorial of num solution 100 648 solution 50 216 solution 10 27 solution 5 3 solution 3 6 solution 2 2 solution 1 1
from math import factorial def solution(num: int = 100) -> int: return sum(int(x) for x in str(factorial(num))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
problem 20 https projecteuler netproblem20 n means n n 1 3 2 1 for example 10 10 9 3 2 1 3628800 and the sum of the digits in the number 10 is 3 6 2 8 8 0 0 27 find the sum of the digits in the number 100 returns the sum of the digits in the factorial of num solution1000 10539 solution200 1404 solution100 648 solution50 216 solution10 27 solution5 3 solution3 6 solution2 2 solution1 1 solution0 1 returns the sum of the digits in the factorial of num solution 1000 10539 solution 200 1404 solution 100 648 solution 50 216 solution 10 27 solution 5 3 solution 3 6 solution 2 2 solution 1 1 solution 0 1
from math import factorial def solution(num: int = 100) -> int: return sum(map(int, str(factorial(num)))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
problem 20 https projecteuler netproblem20 n means n n 1 3 2 1 for example 10 10 9 3 2 1 3628800 and the sum of the digits in the number 10 is 3 6 2 8 8 0 0 27 find the sum of the digits in the number 100 returns the sum of the digits in the factorial of num solution100 648 solution50 216 solution10 27 solution5 3 solution3 6 solution2 2 solution1 1 returns the sum of the digits in the factorial of num solution 100 648 solution 50 216 solution 10 27 solution 5 3 solution 3 6 solution 2 2 solution 1 1
def solution(num: int = 100) -> int: fact = 1 result = 0 for i in range(1, num + 1): fact *= i for j in str(fact): result += int(j) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
amicable numbers problem 21 let dn be defined as the sum of proper divisors of n numbers less than n which divide evenly into n if da b and db a where a b then a and b are an amicable pair and each of a and b are called amicable numbers for example the proper divisors of 220 are 1 2 4 5 10 11 20 22 44 55 and 110 therefore d220 284 the proper divisors of 284 are 1 2 4 71 and 142 so d284 220 evaluate the sum of all the amicable numbers under 10000 returns the sum of all the amicable numbers under n solution10000 31626 solution5000 8442 solution1000 504 solution100 0 solution50 0 returns the sum of all the amicable numbers under n solution 10000 31626 solution 5000 8442 solution 1000 504 solution 100 0 solution 50 0
from math import sqrt def sum_of_divisors(n: int) -> int: total = 0 for i in range(1, int(sqrt(n) + 1)): if n % i == 0 and i != sqrt(n): total += i + n // i elif i == sqrt(n): total += i return total - n def solution(n: int = 10000) -> int: total = sum( i for i in range(1, n) if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
name scores problem 22 using names txt right click and save linktarget as a 46k text file containing over fivethousand first names begin by sorting it into alphabetical order then working out the alphabetical value for each name multiply this value by its alphabetical position in the list to obtain a name score for example when the list is sorted into alphabetical order colin which is worth 3 15 12 9 14 53 is the 938th name in the list so colin would obtain a score of 938 53 49714 what is the total of all the name scores in the file returns the total of all the name scores in the file solution 871198282 returns the total of all the name scores in the file solution 871198282
import os def solution(): with open(os.path.dirname(__file__) + "/p022_names.txt") as file: names = str(file.readlines()[0]) names = names.replace('"', "").split(",") names.sort() name_score = 0 total_score = 0 for i, name in enumerate(names): for letter in name: name_score += ord(letter) - 64 total_score += (i + 1) * name_score name_score = 0 return total_score if __name__ == "__main__": print(solution())
name scores problem 22 using names txt right click and save linktarget as a 46k text file containing over fivethousand first names begin by sorting it into alphabetical order then working out the alphabetical value for each name multiply this value by its alphabetical position in the list to obtain a name score for example when the list is sorted into alphabetical order colin which is worth 3 15 12 9 14 53 is the 938th name in the list so colin would obtain a score of 938 53 49714 what is the total of all the name scores in the file returns the total of all the name scores in the file solution 871198282 returns the total of all the name scores in the file solution 871198282
import os def solution(): total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
a perfect number is a number for which the sum of its proper divisors is exactly equal to the number for example the sum of the proper divisors of 28 would be 1 2 4 7 14 28 which means that 28 is a perfect number a number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n as 12 is the smallest abundant number 1 2 3 4 6 16 the smallest number that can be written as the sum of two abundant numbers is 24 by mathematical analysis it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers however this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit find the sum of all the positive integers which cannot be written as the sum of two abundant numbers finds the sum of all the positive integers which cannot be written as the sum of two abundant numbers as described by the statement above solution 4179871 finds the sum of all the positive integers which cannot be written as the sum of two abundant numbers as described by the statement above solution 4179871
def solution(limit=28123): sum_divs = [1] * (limit + 1) for i in range(2, int(limit**0.5) + 1): sum_divs[i * i] += i for k in range(i + 1, limit // i + 1): sum_divs[k * i] += k + i abundants = set() res = 0 for n in range(1, limit + 1): if sum_divs[n] > n: abundants.add(n) if not any((n - a in abundants) for a in abundants): res += n return res if __name__ == "__main__": print(solution())
a permutation is an ordered arrangement of objects for example 3124 is one possible permutation of the digits 1 2 3 and 4 if all of the permutations are listed numerically or alphabetically we call it lexicographic order the lexicographic permutations of 0 1 and 2 are 012 021 102 120 201 210 what is the millionth lexicographic permutation of the digits 0 1 2 3 4 5 6 7 8 and 9 returns the millionth lexicographic permutation of the digits 0 1 2 3 4 5 6 7 8 and 9 solution 2783915460 returns the millionth lexicographic permutation of the digits 0 1 2 3 4 5 6 7 8 and 9 solution 2783915460
from itertools import permutations def solution(): result = list(map("".join, permutations("0123456789"))) return result[999999] if __name__ == "__main__": print(solution())
the fibonacci sequence is defined by the recurrence relation fn fn1 fn2 where f1 1 and f2 1 hence the first 12 terms will be f1 1 f2 1 f3 2 f4 3 f5 5 f6 8 f7 13 f8 21 f9 34 f10 55 f11 89 f12 144 the 12th term f12 is the first term to contain three digits what is the index of the first term in the fibonacci sequence to contain 1000 digits computes the fibonacci number for input n by iterating through n numbers and creating an array of ints using the fibonacci formula returns the nth element of the array fibonacci2 1 fibonacci3 2 fibonacci5 5 fibonacci10 55 fibonacci12 144 computes incrementing fibonacci numbers starting from 3 until the length of the resulting fibonacci result is the input value n returns the term of the fibonacci sequence where this occurs fibonaccidigitsindex1000 4782 fibonaccidigitsindex100 476 fibonaccidigitsindex50 237 fibonaccidigitsindex3 12 returns the index of the first term in the fibonacci sequence to contain n digits solution1000 4782 solution100 476 solution50 237 solution3 12 computes the fibonacci number for input n by iterating through n numbers and creating an array of ints using the fibonacci formula returns the nth element of the array fibonacci 2 1 fibonacci 3 2 fibonacci 5 5 fibonacci 10 55 fibonacci 12 144 computes incrementing fibonacci numbers starting from 3 until the length of the resulting fibonacci result is the input value n returns the term of the fibonacci sequence where this occurs fibonacci_digits_index 1000 4782 fibonacci_digits_index 100 476 fibonacci_digits_index 50 237 fibonacci_digits_index 3 12 returns the index of the first term in the fibonacci sequence to contain n digits solution 1000 4782 solution 100 476 solution 50 237 solution 3 12
def fibonacci(n: int) -> int: if n == 1 or not isinstance(n, int): return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def fibonacci_digits_index(n: int) -> int: digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index def solution(n: int = 1000) -> int: return fibonacci_digits_index(n) if __name__ == "__main__": print(solution(int(str(input()).strip())))
the fibonacci sequence is defined by the recurrence relation fn fn1 fn2 where f1 1 and f2 1 hence the first 12 terms will be f1 1 f2 1 f3 2 f4 3 f5 5 f6 8 f7 13 f8 21 f9 34 f10 55 f11 89 f12 144 the 12th term f12 is the first term to contain three digits what is the index of the first term in the fibonacci sequence to contain 1000 digits a generator that produces numbers in the fibonacci sequence generator fibonaccigenerator nextgenerator 1 nextgenerator 2 nextgenerator 3 nextgenerator 5 nextgenerator 8 returns the index of the first term in the fibonacci sequence to contain n digits solution1000 4782 solution100 476 solution50 237 solution3 12 a generator that produces numbers in the fibonacci sequence generator fibonacci_generator next generator 1 next generator 2 next generator 3 next generator 5 next generator 8 returns the index of the first term in the fibonacci sequence to contain n digits solution 1000 4782 solution 100 476 solution 50 237 solution 3 12
from collections.abc import Generator def fibonacci_generator() -> Generator[int, None, None]: a, b = 0, 1 while True: a, b = b, a + b yield b def solution(n: int = 1000) -> int: answer = 1 gen = fibonacci_generator() while len(str(next(gen))) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
the fibonacci sequence is defined by the recurrence relation fn fn1 fn2 where f1 1 and f2 1 hence the first 12 terms will be f1 1 f2 1 f3 2 f4 3 f5 5 f6 8 f7 13 f8 21 f9 34 f10 55 f11 89 f12 144 the 12th term f12 is the first term to contain three digits what is the index of the first term in the fibonacci sequence to contain 1000 digits returns the index of the first term in the fibonacci sequence to contain n digits solution1000 4782 solution100 476 solution50 237 solution3 12 returns the index of the first term in the fibonacci sequence to contain n digits solution 1000 4782 solution 100 476 solution 50 237 solution 3 12
def solution(n: int = 1000) -> int: f1, f2 = 1, 1 index = 2 while True: i = 0 f = f1 + f2 f1, f2 = f2, f index += 1 for _ in str(f): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
euler problem 26 https projecteuler netproblem26 problem statement a unit fraction contains 1 in the numerator the decimal representation of the unit fractions with denominators 2 to 10 are given 12 0 5 13 0 3 14 0 25 15 0 2 16 0 16 17 0 142857 18 0 125 19 0 1 110 0 1 where 0 16 means 0 166666 and has a 1digit recurring cycle it can be seen that 17 has a 6digit recurring cycle find the value of d 1000 for which 1d contains the longest recurring cycle in its decimal fraction part considering any range can be provided because as per the problem the digit d 1000 solution1 10 7 solution10 100 97 solution10 1000 983 tests considering any range can be provided because as per the problem the digit d 1000 solution 1 10 7 solution 10 100 97 solution 10 1000 983 tests
def solution(numerator: int = 1, digit: int = 1000) -> int: the_digit = 1 longest_list_length = 0 for divide_by_number in range(numerator, digit + 1): has_been_divided: list[int] = [] now_divide = numerator for _ in range(1, digit + 1): if now_divide in has_been_divided: if longest_list_length < len(has_been_divided): longest_list_length = len(has_been_divided) the_digit = divide_by_number else: has_been_divided.append(now_divide) now_divide = now_divide * 10 % divide_by_number return the_digit if __name__ == "__main__": import doctest doctest.testmod()
project euler problem 27 https projecteuler netproblem27 problem statement euler discovered the remarkable quadratic formula n2 n 41 it turns out that the formula will produce 40 primes for the consecutive values n 0 to 39 however when n 40 402 40 41 4040 1 41 is divisible by 41 and certainly when n 41 412 41 41 is clearly divisible by 41 the incredible formula n2 79n 1601 was discovered which produces 80 primes for the consecutive values n 0 to 79 the product of the coefficients 79 and 1601 is 126479 considering quadratics of the form n an b where a lt 1000 and b lt 1000 where n is the modulusabsolute value of ne g 11 11 and 4 4 find the product of the coefficients a and b for the quadratic expression that produces the maximum number of primes for consecutive values of n starting with n 0 checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number num i e if the result is true then the number is indeed prime else it is not isprime2 true isprime3 true isprime27 false isprime2999 true isprime0 false isprime1 false isprime10 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 solution1000 1000 59231 solution200 1000 59231 solution200 200 4925 solution1000 1000 0 solution1000 1000 0 checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself returns boolean representing primality of given number num i e if the result is true then the number is indeed prime else it is not is_prime 2 true is_prime 3 true is_prime 27 false is_prime 2999 true is_prime 0 false is_prime 1 false is_prime 10 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 solution 1000 1000 59231 solution 200 1000 59231 solution 200 200 4925 solution 1000 1000 0 solution 1000 1000 0 length a b
import math def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(a_limit: int = 1000, b_limit: int = 1000) -> int: longest = [0, 0, 0] for a in range((a_limit * -1) + 1, a_limit): for b in range(2, b_limit): if is_prime(b): count = 0 n = 0 while is_prime((n**2) + (a * n) + b): count += 1 n += 1 if count > longest[0]: longest = [count, a, b] ans = longest[1] * longest[2] return ans if __name__ == "__main__": print(solution(1000, 1000))
problem 28 url https projecteuler netproblem28 statement starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 it can be verified that the sum of the numbers on the diagonals is 101 what is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way returns the sum of the numbers on the diagonals in a n by n spiral formed in the same way solution1001 669171001 solution500 82959497 solution100 651897 solution50 79697 solution10 537 returns the sum of the numbers on the diagonals in a n by n spiral formed in the same way solution 1001 669171001 solution 500 82959497 solution 100 651897 solution 50 79697 solution 10 537
from math import ceil def solution(n: int = 1001) -> int: total = 1 for i in range(1, int(ceil(n / 2.0))): odd = 2 * i + 1 even = 2 * i total = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: n = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number")
consider all integer combinations of ab for 2 a 5 and 2 b 5 224 238 2416 2532 329 3327 3481 35243 4216 4364 44256 451024 5225 53125 54625 553125 if they are then placed in numerical order with any repeats removed we get the following sequence of 15 distinct terms 4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125 how many distinct terms are in the sequence generated by ab for 2 a 100 and 2 b 100 returns the number of distinct terms in the sequence generated by ab for 2 a 100 and 2 b 100 solution100 9183 solution50 2184 solution20 324 solution5 15 solution2 1 solution1 0 returns the number of distinct terms in the sequence generated by a b for 2 a 100 and 2 b 100 solution 100 9183 solution 50 2184 solution 20 324 solution 5 15 solution 2 1 solution 1 0 maximum limit calculates the current power adds the result to the set
def solution(n: int = 100) -> int: collect_powers = set() current_pow = 0 n = n + 1 for a in range(2, n): for b in range(2, n): current_pow = a**b collect_powers.add(current_pow) return len(collect_powers) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
problem statement digit fifth powers https projecteuler netproblem30 surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits 1634 14 64 34 44 8208 84 24 04 84 9474 94 44 74 44 as 1 14 is not a sum it is not included the sum of these numbers is 1634 8208 9474 19316 find the sum of all the numbers that can be written as the sum of fifth powers of their digits 95 59049 59049 7 413343 which is only 6 digit number so numbers greater than 999999 are rejected and also 59049 3 177147 which exceeds the criteria of number being 3 digit so number 999 and hence a number between 1000 and 1000000 digitsfifthpowerssum1234 1300 digits_fifth_powers_sum 1234 1300
DIGITS_FIFTH_POWER = {str(digit): digit**5 for digit in range(10)} def digits_fifth_powers_sum(number: int) -> int: return sum(DIGITS_FIFTH_POWER[digit] for digit in str(number)) def solution() -> int: return sum( number for number in range(1000, 1000000) if number == digits_fifth_powers_sum(number) ) if __name__ == "__main__": print(solution())
coin sums problem 31 https projecteuler netproblem31 in england the currency is made up of pound and pence p and there are eight coins in general circulation 1p 2p 5p 10p 20p 50p 1 100p and 2 200p it is possible to make 2 in the following way 11 150p 220p 15p 12p 31p how many different ways can 2 be made using any number of coins returns the number of different ways can n pence be made using any number of coins solution500 6295434 solution200 73682 solution50 451 solution10 11 returns the number of different ways can n pence be made using any number of coins solution 500 6295434 solution 200 73682 solution 50 451 solution 10 11
def one_pence() -> int: return 1 def two_pence(x: int) -> int: return 0 if x < 0 else two_pence(x - 2) + one_pence() def five_pence(x: int) -> int: return 0 if x < 0 else five_pence(x - 5) + two_pence(x) def ten_pence(x: int) -> int: return 0 if x < 0 else ten_pence(x - 10) + five_pence(x) def twenty_pence(x: int) -> int: return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x) def fifty_pence(x: int) -> int: return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x) def one_pound(x: int) -> int: return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x) def two_pound(x: int) -> int: return 0 if x < 0 else two_pound(x - 200) + one_pound(x) def solution(n: int = 200) -> int: return two_pound(n) if __name__ == "__main__": print(solution(int(input().strip())))
problem 31 https projecteuler netproblem31 coin sums in england the currency is made up of pound and pence p and there are eight coins in general circulation 1p 2p 5p 10p 20p 50p 1 100p and 2 200p it is possible to make 2 in the following way 11 150p 220p 15p 12p 31p how many different ways can 2 be made using any number of coins hint there are 100 pence in a pound 1 100p there are coinsin pence are available 1 2 5 10 20 50 100 and 200 how many different ways you can combine these values to create 200 pence example to make 6p there are 5 ways 1 1 1 1 1 1 1 1 1 1 2 1 1 2 2 2 2 2 1 5 to make 5p there are 4 ways 1 1 1 1 1 1 1 1 2 1 2 2 5 returns the number of different ways to make x pence using any number of coins the solution is based on dynamic programming paradigm in a bottomup fashion solution500 6295434 solution200 73682 solution50 451 solution10 11 returns the number of different ways to make x pence using any number of coins the solution is based on dynamic programming paradigm in a bottom up fashion solution 500 6295434 solution 200 73682 solution 50 451 solution 10 11 base case 1 way to make 0 pence
def solution(pence: int = 200) -> int: coins = [1, 2, 5, 10, 20, 50, 100, 200] number_of_ways = [0] * (pence + 1) number_of_ways[0] = 1 for coin in coins: for i in range(coin, pence + 1, 1): number_of_ways[i] += number_of_ways[i - coin] return number_of_ways[pence] if __name__ == "__main__": assert solution(200) == 73682
we shall say that an ndigit number is pandigital if it makes use of all the digits 1 to n exactly once for example the 5digit number 15234 is 1 through 5 pandigital the product 7254 is unusual as the identity 39 186 7254 containing multiplicand multiplier and product is 1 through 9 pandigital find the sum of all products whose multiplicandmultiplierproduct identity can be written as a 1 through 9 pandigital hint some products can be obtained in more than one way so be sure to only include it once in your sum checks if a combination a tuple of 9 digits is a valid product equation iscombinationvalid 3 9 1 8 6 7 2 5 4 true iscombinationvalid 1 2 3 4 5 6 7 8 9 false finds the sum of all products whose multiplicandmultiplierproduct identity can be written as a 1 through 9 pandigital solution 45228 checks if a combination a tuple of 9 digits is a valid product equation is_combination_valid 3 9 1 8 6 7 2 5 4 true is_combination_valid 1 2 3 4 5 6 7 8 9 false finds the sum of all products whose multiplicand multiplier product identity can be written as a 1 through 9 pandigital solution 45228
import itertools def is_combination_valid(combination): return ( int("".join(combination[0:2])) * int("".join(combination[2:5])) == int("".join(combination[5:9])) ) or ( int("".join(combination[0])) * int("".join(combination[1:5])) == int("".join(combination[5:9])) ) def solution(): return sum( { int("".join(pandigital[5:9])) for pandigital in itertools.permutations("123456789") if is_combination_valid(pandigital) } ) if __name__ == "__main__": print(solution())
problem 33 https projecteuler netproblem33 the fraction 4998 is a curious fraction as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 4998 48 which is correct is obtained by cancelling the 9s we shall consider fractions like 3050 35 to be trivial examples there are exactly four nontrivial examples of this type of fraction less than one in value and containing two digits in the numerator and denominator if the product of these four fractions is given in its lowest common terms find the value of the denominator fractionlist2 1664 1995 2665 4998 fractionlist3 1664 1995 2665 4998 fractionlist4 1664 1995 2665 4998 fractionlist0 fractionlist5 1664 1995 2665 4998 return the solution to the problem fraction_list 2 16 64 19 95 26 65 49 98 fraction_list 3 16 64 19 95 26 65 49 98 fraction_list 4 16 64 19 95 26 65 49 98 fraction_list 0 fraction_list 5 16 64 19 95 26 65 49 98 return the solution to the problem
from __future__ import annotations from fractions import Fraction def is_digit_cancelling(num: int, den: int) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def fraction_list(digit_len: int) -> list[str]: solutions = [] den = 11 last_digit = int("1" + "0" * digit_len) for num in range(den, last_digit): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(num, den): solutions.append(f"{num}/{den}") den += 1 num += 1 den = 10 return solutions def solution(n: int = 2) -> int: result = 1.0 for fraction in fraction_list(n): frac = Fraction(fraction) result *= frac.denominator / frac.numerator return int(result) if __name__ == "__main__": print(solution())
problem 34 https projecteuler netproblem34 145 is a curious number as 1 4 5 1 24 120 145 find the sum of all numbers which are equal to the sum of the factorial of their digits note as 1 1 and 2 2 are not sums they are not included returns the sum of the factorial of digits in n sumofdigitfactorial15 121 sumofdigitfactorial0 1 returns the sum of all numbers whose sum of the factorials of all digits add up to the number itself solution 40730 returns the sum of the factorial of digits in n sum_of_digit_factorial 15 121 sum_of_digit_factorial 0 1 returns the sum of all numbers whose sum of the factorials of all digits add up to the number itself solution 40730
from math import factorial DIGIT_FACTORIAL = {str(d): factorial(d) for d in range(10)} def sum_of_digit_factorial(n: int) -> int: return sum(DIGIT_FACTORIAL[d] for d in str(n)) def solution() -> int: limit = 7 * factorial(9) + 1 return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 35 https projecteuler netproblem35 problem statement the number 197 is called a circular prime because all rotations of the digits 197 971 and 719 are themselves prime there are thirteen such primes below 100 2 3 5 7 11 13 17 31 37 71 73 79 and 97 how many circular primes are there below one million to solve this problem in an efficient manner we will first mark all the primes below 1 million using the sieve of eratosthenes then out of all these primes we will rule out the numbers which contain an even digit after this we will generate each circular combination of the number and check if all are prime for 2 n 1000000 return true if n is prime isprime87 false isprime23 true isprime25363 false return true if n contains an even digit containsanevendigit0 true containsanevendigit975317933 false containsanevendigit245679 true return circular primes below limit lenfindcircularprimes100 13 lenfindcircularprimes1000000 55 solution 55 for 2 n 1000000 return true if n is prime is_prime 87 false is_prime 23 true is_prime 25363 false return true if n contains an even digit contains_an_even_digit 0 true contains_an_even_digit 975317933 false contains_an_even_digit 245679 true return circular primes below limit len find_circular_primes 100 13 len find_circular_primes 1000000 55 result already includes the number 2 solution 55
from __future__ import annotations sieve = [True] * 1000001 i = 2 while i * i <= 1000000: if sieve[i]: for j in range(i * i, 1000001, i): sieve[j] = False i += 1 def is_prime(n: int) -> bool: return sieve[n] def contains_an_even_digit(n: int) -> bool: return any(digit in "02468" for digit in str(n)) def find_circular_primes(limit: int = 1000000) -> list[int]: result = [2] for num in range(3, limit + 1, 2): if is_prime(num) and not contains_an_even_digit(num): str_num = str(num) list_nums = [int(str_num[j:] + str_num[:j]) for j in range(len(str_num))] if all(is_prime(i) for i in list_nums): result.append(num) return result def solution() -> int: return len(find_circular_primes()) if __name__ == "__main__": print(f"{len(find_circular_primes()) = }")
project euler problem 36 https projecteuler netproblem36 problem statement doublebase palindromes problem 36 the decimal number 585 10010010012 binary is palindromic in both bases find the sum of all numbers less than one million which are palindromic in base 10 and base 2 please note that the palindromic number in either base may not include leading zeros return true if the input n is a palindrome otherwise return false n can be an integer or a string ispalindrome909 true ispalindrome908 false ispalindrome 10101 true ispalindrome 10111 false return the sum of all numbers less than n which are palindromic in base 10 and base 2 solution1000000 872187 solution500000 286602 solution100000 286602 solution1000 1772 solution100 157 solution10 25 solution2 1 solution1 0 return true if the input n is a palindrome otherwise return false n can be an integer or a string is_palindrome 909 true is_palindrome 908 false is_palindrome 10101 true is_palindrome 10111 false return the sum of all numbers less than n which are palindromic in base 10 and base 2 solution 1000000 872187 solution 500000 286602 solution 100000 286602 solution 1000 1772 solution 100 157 solution 10 25 solution 2 1 solution 1 0
from __future__ import annotations def is_palindrome(n: int | str) -> bool: n = str(n) return n == n[::-1] def solution(n: int = 1000000): total = 0 for i in range(1, n): if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
truncatable primes problem 37 https projecteuler netproblem37 the number 3797 has an interesting property being prime itself it is possible to continuously remove digits from left to right and remain prime at each stage 3797 797 97 and 7 similarly we can work from right to left 3797 379 37 and 3 find the sum of the only eleven primes that are both truncatable from left to right and right to left note 2 3 5 and 7 are not considered to be truncatable primes checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself isprime0 false isprime1 false isprime2 true isprime3 true isprime27 false isprime87 false isprime563 true isprime2999 true isprime67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns a list of all left and right truncated numbers of n listtruncatednums927628 927628 27628 92762 7628 9276 628 927 28 92 8 9 listtruncatednums467 467 67 46 7 4 listtruncatednums58 58 8 5 to optimize the approach we will rule out the numbers above 1000 whose first or last three digits are not prime validate74679 false validate235693 false validate3797 true returns the list of truncated primes computetruncatedprimes11 23 37 53 73 313 317 373 797 3137 3797 739397 returns the sum of truncated primes checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself is_prime 0 false is_prime 1 false is_prime 2 true is_prime 3 true is_prime 27 false is_prime 87 false is_prime 563 true is_prime 2999 true is_prime 67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns a list of all left and right truncated numbers of n list_truncated_nums 927628 927628 27628 92762 7628 9276 628 927 28 92 8 9 list_truncated_nums 467 467 67 46 7 4 list_truncated_nums 58 58 8 5 to optimize the approach we will rule out the numbers above 1000 whose first or last three digits are not prime validate 74679 false validate 235693 false validate 3797 true returns the list of truncated primes compute_truncated_primes 11 23 37 53 73 313 317 373 797 3137 3797 739397 returns the sum of truncated primes
from __future__ import annotations import math def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def list_truncated_nums(n: int) -> list[int]: str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
project euler problem 38 https projecteuler netproblem38 take the number 192 and multiply it by each of 1 2 and 3 192 1 192 192 2 384 192 3 576 by concatenating each product we get the 1 to 9 pandigital 192384576 we will call 192384576 the concatenated product of 192 and 1 2 3 the same can be achieved by starting with 9 and multiplying by 1 2 3 4 and 5 giving the pandigital 918273645 which is the concatenated product of 9 and 1 2 3 4 5 what is the largest 1 to 9 pandigital 9digit number that can be formed as the concatenated product of an integer with 1 2 n where n 1 solution since n1 the largest candidate for the solution will be a concactenation of a 4digit number and its double a 5digit number let a be the 4digit number a has 4 digits 1000 a 10000 2a has 5 digits 10000 2a 100000 5000 a 10000 the concatenation of a with 2a a 105 2a so our candidate for a given a is 100002 a we iterate through the search space 5000 a 10000 in reverse order calculating the candidates for each a and checking if they are 19 pandigital in case there are no 4digit numbers that satisfy this property we check the 3digit numbers with a similar formula the example a192 gives a lower bound on the length of a a has 3 digits etc 100 a 334 candidate a 106 2a 103 3a 1002003 a checks whether n is a 9digit 1 to 9 pandigital number is9pandigital12345 false is9pandigital156284973 true is9pandigital1562849733 false return the largest 1 to 9 pandigital 9digital number that can be formed as the concatenated product of an integer with 1 2 n where n 1 checks whether n is a 9 digit 1 to 9 pandigital number is_9_pandigital 12345 false is_9_pandigital 156284973 true is_9_pandigital 1562849733 false return the largest 1 to 9 pandigital 9 digital number that can be formed as the concatenated product of an integer with 1 2 n where n 1
from __future__ import annotations def is_9_pandigital(n: int) -> bool: s = str(n) return len(s) == 9 and set(s) == set("123456789") def solution() -> int | None: for base_num in range(9999, 4999, -1): candidate = 100002 * base_num if is_9_pandigital(candidate): return candidate for base_num in range(333, 99, -1): candidate = 1002003 * base_num if is_9_pandigital(candidate): return candidate return None if __name__ == "__main__": print(f"{solution() = }")
problem 39 https projecteuler netproblem39 if p is the perimeter of a right angle triangle with integral length sides a b c there are exactly three solutions for p 120 20 48 52 24 45 51 30 40 50 for which value of p 1000 is the number of solutions maximised returns a dictionary with keys as the perimeter of a right angled triangle and value as the number of corresponding triplets pythagoreantriple15 counter12 1 pythagoreantriple40 counter12 1 30 1 24 1 40 1 36 1 pythagoreantriple50 counter12 1 30 1 24 1 40 1 36 1 48 1 returns perimeter with maximum solutions solution100 90 solution200 180 solution1000 840 returns a dictionary with keys as the perimeter of a right angled triangle and value as the number of corresponding triplets pythagorean_triple 15 counter 12 1 pythagorean_triple 40 counter 12 1 30 1 24 1 40 1 36 1 pythagorean_triple 50 counter 12 1 30 1 24 1 40 1 36 1 48 1 returns perimeter with maximum solutions solution 100 90 solution 200 180 solution 1000 840
from __future__ import annotations import typing from collections import Counter def pythagorean_triple(max_perimeter: int) -> typing.Counter[int]: triplets: typing.Counter[int] = Counter() for base in range(1, max_perimeter + 1): for perpendicular in range(base, max_perimeter + 1): hypotenuse = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(hypotenuse): perimeter = int(base + perpendicular + hypotenuse) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def solution(n: int = 1000) -> int: triplets = pythagorean_triple(n) return triplets.most_common(1)[0][0] if __name__ == "__main__": print(f"Perimeter {solution()} has maximum solutions")
champernowne s constant problem 40 an irrational decimal fraction is concatenating the positive integers 0 123456789101112131415161718192021 it can be seen that the 12th digit of the fractional part is 1 if dn represents the nth digit of the fractional part find the value of the following expression d1 d10 d100 d1000 d10000 d100000 d1000000 returns solution 210 returns solution 210
def solution(): constant = [] i = 1 while len(constant) < 1e6: constant.append(str(i)) i += 1 constant = "".join(constant) return ( int(constant[0]) * int(constant[9]) * int(constant[99]) * int(constant[999]) * int(constant[9999]) * int(constant[99999]) * int(constant[999999]) ) if __name__ == "__main__": print(solution())
pandigital prime problem 41 https projecteuler netproblem41 we shall say that an ndigit number is pandigital if it makes use of all the digits 1 to n exactly once for example 2143 is a 4digit pandigital and is also prime what is the largest ndigit pandigital prime that exists all pandigital numbers except for 1 4 7 pandigital numbers are divisible by 3 so we will check only 7 digit pandigital numbers to obtain the largest possible pandigital prime checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself isprime0 false isprime1 false isprime2 true isprime3 true isprime27 false isprime87 false isprime563 true isprime2999 true isprime67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the maximum pandigital prime number of length n if there are none then it will return 0 solution2 0 solution4 4231 solution7 7652413 checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself is_prime 0 false is_prime 1 false is_prime 2 true is_prime 3 true is_prime 27 false is_prime 87 false is_prime 563 true is_prime 2999 true is_prime 67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the maximum pandigital prime number of length n if there are none then it will return 0 solution 2 0 solution 4 4231 solution 7 7652413
from __future__ import annotations import math from itertools import permutations def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(n: int = 7) -> int: pandigital_str = "".join(str(i) for i in range(1, n + 1)) perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)] pandigitals = [num for num in perm_list if is_prime(num)] return max(pandigitals) if pandigitals else 0 if __name__ == "__main__": print(f"{solution() = }")
the nth term of the sequence of triangle numbers is given by tn nn1 so the first ten triangle numbers are 1 3 6 10 15 21 28 36 45 55 by converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value for example the word value for sky is 19 11 25 55 t10 if the word value is a triangle number then we shall call the word a triangle word using words txt right click and save linktarget as a 16k text file containing nearly twothousand common english words how many are triangle words precomputes a list of the 100 first triangular numbers finds the amount of triangular words in the words file solution 162 precomputes a list of the 100 first triangular numbers finds the amount of triangular words in the words file solution 162
import os TRIANGULAR_NUMBERS = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def solution(): script_dir = os.path.dirname(os.path.realpath(__file__)) words_file_path = os.path.join(script_dir, "words.txt") words = "" with open(words_file_path) as f: words = f.readline() words = [word.strip('"') for word in words.strip("\r\n").split(",")] words = [ word for word in [sum(ord(x) - 64 for x in word) for word in words] if word in TRIANGULAR_NUMBERS ] return len(words) if __name__ == "__main__": print(solution())
problem 43 https projecteuler netproblem43 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 substring divisibility property let d1 be the 1st digit d2 be the 2nd digit and so on in this way we note the following d2d3d4406 is divisible by 2 d3d4d5063 is divisible by 3 d4d5d6635 is divisible by 5 d5d6d7357 is divisible by 7 d6d7d8572 is divisible by 11 d7d8d9728 is divisible by 13 d8d9d10289 is divisible by 17 find the sum of all 0 to 9 pandigital numbers with this property returns true if the pandigital number passes all the divisibility tests issubstringdivisible0 1 2 4 6 5 7 3 8 9 false issubstringdivisible5 1 2 4 6 0 7 8 3 9 false issubstringdivisible1 4 0 6 3 5 7 2 8 9 true returns the sum of all pandigital numbers which pass the divisibility tests solution10 16695334890 returns true if the pandigital number passes all the divisibility tests is_substring_divisible 0 1 2 4 6 5 7 3 8 9 false is_substring_divisible 5 1 2 4 6 0 7 8 3 9 false is_substring_divisible 1 4 0 6 3 5 7 2 8 9 true returns the sum of all pandigital numbers which pass the divisibility tests solution 10 16695334890
from itertools import permutations def is_substring_divisible(num: tuple) -> bool: if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False tests = [7, 11, 13, 17] for i, test in enumerate(tests): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def solution(n: int = 10) -> int: return sum( int("".join(map(str, num))) for num in permutations(range(n)) if is_substring_divisible(num) ) if __name__ == "__main__": print(f"{solution() = }")
problem 44 https projecteuler netproblem44 pentagonal numbers are generated by the formula pnn3n12 the first ten pentagonal numbers are 1 5 12 22 35 51 70 92 117 145 it can be seen that p4 p7 22 70 92 p8 however their difference 70 22 48 is not pentagonal find the pair of pentagonal numbers pj and pk for which their sum and difference are pentagonal and d pk pj is minimised what is the value of d returns true if n is pentagonal false otherwise ispentagonal330 true ispentagonal7683 false ispentagonal2380 true returns the minimum difference of two pentagonal numbers p1 and p2 such that p1 p2 is pentagonal and p2 p1 is pentagonal solution5000 5482660 returns true if n is pentagonal false otherwise is_pentagonal 330 true is_pentagonal 7683 false is_pentagonal 2380 true returns the minimum difference of two pentagonal numbers p1 and p2 such that p1 p2 is pentagonal and p2 p1 is pentagonal solution 5000 5482660
def is_pentagonal(n: int) -> bool: root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(limit: int = 5000) -> int: pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] for i, pentagonal_i in enumerate(pentagonal_nums): for j in range(i, len(pentagonal_nums)): pentagonal_j = pentagonal_nums[j] a = pentagonal_i + pentagonal_j b = pentagonal_j - pentagonal_i if is_pentagonal(a) and is_pentagonal(b): return b return -1 if __name__ == "__main__": print(f"{solution() = }")
problem 45 https projecteuler netproblem45 triangle pentagonal and hexagonal numbers are generated by the following formulae triangle tn n n 1 2 1 3 6 10 15 pentagonal pn n 3 n 1 2 1 5 12 22 35 hexagonal hn n 2 n 1 1 6 15 28 45 it can be verified that t285 p165 h143 40755 find the next triangle number that is also pentagonal and hexagonal all triangle numbers are hexagonal numbers t2n1 n 2 n 1 hn so we shall check only for hexagonal numbers which are also pentagonal returns nth hexagonal number hexagonalnum143 40755 hexagonalnum21 861 hexagonalnum10 190 returns true if n is pentagonal false otherwise ispentagonal330 true ispentagonal7683 false ispentagonal2380 true returns the next number which is triangular pentagonal and hexagonal solution144 1533776805 returns nth hexagonal number hexagonal_num 143 40755 hexagonal_num 21 861 hexagonal_num 10 190 returns true if n is pentagonal false otherwise is_pentagonal 330 true is_pentagonal 7683 false is_pentagonal 2380 true returns the next number which is triangular pentagonal and hexagonal solution 144 1533776805
def hexagonal_num(n: int) -> int: return n * (2 * n - 1) def is_pentagonal(n: int) -> bool: root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(start: int = 144) -> int: n = start num = hexagonal_num(n) while not is_pentagonal(num): n += 1 num = hexagonal_num(n) return num if __name__ == "__main__": print(f"{solution()} = ")
problem 46 https projecteuler netproblem46 it was proposed by christian goldbach that every odd composite number can be written as the sum of a prime and twice a square 9 7 2 12 15 7 2 22 21 3 2 32 25 7 2 32 27 19 2 22 33 31 2 12 it turns out that the conjecture was false what is the smallest odd composite that cannot be written as the sum of a prime and twice a square checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself isprime0 false isprime1 false isprime2 true isprime3 true isprime27 false isprime87 false isprime563 true isprime2999 true isprime67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns a list of first n odd composite numbers which do not follow the conjecture computenums1 5777 computenums2 5777 5993 computenums0 traceback most recent call last valueerror n must be 0 computenumsa traceback most recent call last valueerror n must be an integer computenums1 1 traceback most recent call last valueerror n must be an integer return the solution to the problem return computenums10 if name main printfsolution checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself is_prime 0 false is_prime 1 false is_prime 2 true is_prime 3 true is_prime 27 false is_prime 87 false is_prime 563 true is_prime 2999 true is_prime 67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns a list of first n odd composite numbers which do not follow the conjecture compute_nums 1 5777 compute_nums 2 5777 5993 compute_nums 0 traceback most recent call last valueerror n must be 0 compute_nums a traceback most recent call last valueerror n must be an integer compute_nums 1 1 traceback most recent call last valueerror n must be an integer return the solution to the problem
from __future__ import annotations import math def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True odd_composites = [num for num in range(3, 100001, 2) if not is_prime(num)] def compute_nums(n: int) -> list[int]: if not isinstance(n, int): raise ValueError("n must be an integer") if n <= 0: raise ValueError("n must be >= 0") list_nums = [] for num in range(len(odd_composites)): i = 0 while 2 * i * i <= odd_composites[num]: rem = odd_composites[num] - 2 * i * i if is_prime(rem): break i += 1 else: list_nums.append(odd_composites[num]) if len(list_nums) == n: return list_nums return [] def solution() -> int: return compute_nums(1)[0] if __name__ == "__main__": print(f"{solution() = }")
combinatoric selections problem 47 the first two consecutive numbers to have two distinct prime factors are 14 2 7 15 3 5 the first three consecutive numbers to have three distinct prime factors are 644 2 7 23 645 3 5 43 646 2 17 19 find the first four consecutive integers to have four distinct prime factors each what is the first of these numbers find unique prime factors of an integer tests include sorting because only the set really matters not the order in which it is produced sortedsetuniqueprimefactors14 2 7 sortedsetuniqueprimefactors644 2 7 23 sortedsetuniqueprimefactors646 2 17 19 memoize upf length results for a given value upflen14 2 check equality of all elements in an interable equality1 2 3 4 false equality2 2 2 2 true equality1 2 3 2 1 false runs core process to find problem solution run3 644 645 646 incrementor variable for our group list comprehension this serves as the first number in each list of values to test increment each value of a generated range run elements through out uniqueprimefactors function append our target number to the end if all numbers in the list are equal return the group variable increment our base variable by 1 return the first value of the first four consecutive integers to have four distinct prime factors each solution 134043 find unique prime factors of an integer tests include sorting because only the set really matters not the order in which it is produced sorted set unique_prime_factors 14 2 7 sorted set unique_prime_factors 644 2 7 23 sorted set unique_prime_factors 646 2 17 19 memoize upf length results for a given value upf_len 14 2 check equality of all elements in an interable equality 1 2 3 4 false equality 2 2 2 2 true equality 1 2 3 2 1 false runs core process to find problem solution run 3 644 645 646 incrementor variable for our group list comprehension this serves as the first number in each list of values to test increment each value of a generated range run elements through out unique_prime_factors function append our target number to the end if all numbers in the list are equal return the group variable increment our base variable by 1 return the first value of the first four consecutive integers to have four distinct prime factors each solution 134043
from functools import lru_cache def unique_prime_factors(n: int) -> set: i = 2 factors = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(i) if n > 1: factors.add(n) return factors @lru_cache def upf_len(num: int) -> int: return len(unique_prime_factors(num)) def equality(iterable: list) -> bool: return len(set(iterable)) in (0, 1) def run(n: int) -> list: base = 2 while True: group = [base + i for i in range(n)] checker = [upf_len(x) for x in group] checker.append(n) if equality(checker): return group base += 1 def solution(n: int = 4) -> int: results = run(n) return results[0] if len(results) else None if __name__ == "__main__": print(solution())
self powers problem 48 the series 11 22 33 1010 10405071317 find the last ten digits of the series 11 22 33 10001000 returns the last 10 digits of the series 11 22 33 10001000 solution 9110846700 returns the last 10 digits of the series 1 1 2 2 3 3 1000 1000 solution 9110846700
def solution(): total = 0 for i in range(1, 1001): total += i**i return str(total)[-10:] if __name__ == "__main__": print(solution())
prime permutations problem 49 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 ii each of the 4digit numbers are permutations of one another there are no arithmetic sequences made up of three 1 2 or 3digit primes exhibiting this property but there is one other 4digit increasing sequence what 12digit number do you form by concatenating the three terms in this sequence solution first we need to generate all 4 digits prime numbers then greedy all of them and use permutation to form new numbers use binary search to check if the permutated numbers is in our prime list and include them in a candidate list after that bruteforce all passed candidates sequences using 3 nested loops since we know the answer will be 12 digits the bruteforce of this solution will be about 1 sec checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself isprime0 false isprime1 false isprime2 true isprime3 true isprime27 false isprime87 false isprime563 true isprime2999 true isprime67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 function to search a number in a list using binary search search3 1 2 3 true search4 1 2 3 false search101 listrange100 100 false return the solution of the problem solution 296962999629 checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself is_prime 0 false is_prime 1 false is_prime 2 true is_prime 3 true is_prime 27 false is_prime 87 false is_prime 563 true is_prime 2999 true is_prime 67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 function to search a number in a list using binary search search 3 1 2 3 true search 4 1 2 3 false search 101 list range 100 100 false return the solution of the problem solution 296962999629
import math from itertools import permutations def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def search(target: int, prime_list: list) -> bool: left, right = 0, len(prime_list) - 1 while left <= right: middle = (left + right) // 2 if prime_list[middle] == target: return True elif prime_list[middle] < target: left = middle + 1 else: right = middle - 1 return False def solution(): prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)] candidates = [] for number in prime_list: tmp_numbers = [] for prime_member in permutations(list(str(number))): prime = int("".join(prime_member)) if prime % 2 == 0: continue if search(prime, prime_list): tmp_numbers.append(prime) tmp_numbers.sort() if len(tmp_numbers) >= 3: candidates.append(tmp_numbers) passed = [] for candidate in candidates: length = len(candidate) found = False for i in range(length): for j in range(i + 1, length): for k in range(j + 1, length): if ( abs(candidate[i] - candidate[j]) == abs(candidate[j] - candidate[k]) and len({candidate[i], candidate[j], candidate[k]}) == 3 ): passed.append( sorted([candidate[i], candidate[j], candidate[k]]) ) found = True if found: break if found: break if found: break answer = set() for seq in passed: answer.add("".join([str(i) for i in seq])) return max(int(x) for x in answer) if __name__ == "__main__": print(solution())
project euler problem 50 https projecteuler netproblem50 consecutive prime sum the prime 41 can be written as the sum of six consecutive primes 41 2 3 5 7 11 13 this is the longest sum of consecutive primes that adds to a prime below onehundred the longest sum of consecutive primes below onethousand that adds to a prime contains 21 terms and is equal to 953 which prime below onemillion can be written as the sum of the most consecutive primes sieve of erotosthenes function to return all the prime numbers up to a number limit https en wikipedia orgwikisieveoferatosthenes primesieve3 2 primesieve50 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 returns the biggest prime below the celing that can be written as the sum of consecutive the most consecutive primes solution500 499 solution1000 953 solution10000 9521 sieve of erotosthenes function to return all the prime numbers up to a number limit https en wikipedia org wiki sieve_of_eratosthenes prime_sieve 3 2 prime_sieve 50 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 returns the biggest prime below the celing that can be written as the sum of consecutive the most consecutive primes solution 500 499 solution 1_000 953 solution 10_000 9521
from __future__ import annotations def prime_sieve(limit: int) -> list[int]: is_prime = [True] * limit is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(limit**0.5 + 1), 2): index = i * 2 while index < limit: is_prime[index] = False index = index + i primes = [2] for i in range(3, limit, 2): if is_prime[i]: primes.append(i) return primes def solution(ceiling: int = 1_000_000) -> int: primes = prime_sieve(ceiling) length = 0 largest = 0 for i in range(len(primes)): for j in range(i + length, len(primes)): sol = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: length = j - i largest = sol return largest if __name__ == "__main__": print(f"{solution() = }")
https projecteuler netproblem51 prime digit replacements problem 51 by replacing the 1st digit of the 2digit number 3 it turns out that six of the nine possible values 13 23 43 53 73 and 83 are all prime by replacing the 3rd and 4th digits of 563 with the same digit this 5digit number is the first example having seven primes among the ten generated numbers yielding the family 56003 56113 56333 56443 56663 56773 and 56993 consequently 56003 being the first member of this family is the smallest prime with this property find the smallest prime which by replacing part of the number not necessarily adjacent digits with the same digit is part of an eight prime value family sieve of erotosthenes function to return all the prime numbers up to a certain number https en wikipedia orgwikisieveoferatosthenes primesieve3 2 primesieve50 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 returns all the possible families of digit replacements in a number which contains at least one repeating digit digitreplacements544 500 511 522 533 544 555 566 577 588 599 digitreplacements3112 3002 3112 3222 3332 3442 3552 3662 3772 3882 3992 returns the solution of the problem solution2 229399 solution3 221311 filter primes with less than 3 replaceable digits sieve of erotosthenes function to return all the prime numbers up to a certain number https en wikipedia org wiki sieve_of_eratosthenes prime_sieve 3 2 prime_sieve 50 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 returns all the possible families of digit replacements in a number which contains at least one repeating digit digit_replacements 544 500 511 522 533 544 555 566 577 588 599 digit_replacements 3112 3002 3112 3222 3332 3442 3552 3662 3772 3882 3992 returns the solution of the problem solution 2 229399 solution 3 221311 filter primes with less than 3 replaceable digits
from __future__ import annotations from collections import Counter def prime_sieve(n: int) -> list[int]: is_prime = [True] * n is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(n**0.5 + 1), 2): index = i * 2 while index < n: is_prime[index] = False index = index + i primes = [2] for i in range(3, n, 2): if is_prime[i]: primes.append(i) return primes def digit_replacements(number: int) -> list[list[int]]: number_str = str(number) replacements = [] digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] for duplicate in Counter(number_str) - Counter(set(number_str)): family = [int(number_str.replace(duplicate, digit)) for digit in digits] replacements.append(family) return replacements def solution(family_length: int = 8) -> int: numbers_checked = set() primes = { x for x in set(prime_sieve(1_000_000)) if len(str(x)) - len(set(str(x))) >= 3 } for prime in primes: if prime in numbers_checked: continue replacements = digit_replacements(prime) for family in replacements: numbers_checked.update(family) primes_in_family = primes.intersection(family) if len(primes_in_family) != family_length: continue return min(primes_in_family) return -1 if __name__ == "__main__": print(solution())
permuted multiples problem 52 it can be seen that the number 125874 and its double 251748 contain exactly the same digits but in a different order find the smallest positive integer x such that 2x 3x 4x 5x and 6x contain the same digits returns the smallest positive integer x such that 2x 3x 4x 5x and 6x contain the same digits solution 142857 returns the smallest positive integer x such that 2x 3x 4x 5x and 6x contain the same digits solution 142857
def solution(): i = 1 while True: if ( sorted(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)) ): return i i += 1 if __name__ == "__main__": print(solution())
combinatoric selections problem 53 there are exactly ten ways of selecting three from five 12345 123 124 125 134 135 145 234 235 245 and 345 in combinatorics we use the notation 5c3 10 in general ncr n r nr where r n n nn1 321 and 0 1 it is not until n 23 that a value exceeds onemillion 23c10 1144066 how many not necessarily distinct values of ncr for 1 n 100 are greater than onemillion returns the number of values of ncr for 1 n 100 are greater than onemillion solution 4075 returns the number of values of ncr for 1 n 100 are greater than one million solution 4075
from math import factorial def combinations(n, r): return factorial(n) / (factorial(r) * factorial(n - r)) def solution(): total = 0 for i in range(1, 101): for j in range(1, i + 1): if combinations(i, j) > 1e6: total += 1 return total if __name__ == "__main__": print(solution())
problem https projecteuler netproblem54 in the card game poker a hand consists of five cards and are ranked from lowest to highest in the following way high card highest value card one pair two cards of the same value two pairs two different pairs three of a kind three cards of the same value straight all cards are consecutive values flush all cards of the same suit full house three of a kind and a pair four of a kind four cards of the same value straight flush all cards are consecutive values of same suit royal flush ten jack queen king ace in same suit the cards are valued in the order 2 3 4 5 6 7 8 9 10 jack queen king ace if two players have the same ranked hands then the rank made up of the highest value wins for example a pair of eights beats a pair of fives but if two ranks tie for example both players have a pair of queens then highest cards in each hand are compared if the highest cards tie then the next highest cards are compared and so on the file poker txt contains onethousand random hands dealt to two players each line of the file contains ten cards separated by a single space the first five are player 1 s cards and the last five are player 2 s cards you can assume that all hands are valid no invalid characters or repeated cards each player s hand is in no specific order and in each hand there is a clear winner how many hands does player 1 win resources used https en wikipedia orgwikitexashold27em https en wikipedia orgwikilistofpokerhands similar problem on codewars https www codewars comkatarankingpokerhands https www codewars comkatasortablepokerhands create an object representing a poker hand based on an input of a string which represents the best 5card combination from the player s hand and board cards attributes readonly hand a string representing the hand consisting of five cards methods comparewithopponent takes in player s hand self and opponent s hand opponent and compares both hands according to the rules of texas hold em returns one of 3 strings win loss tie based on whether player s hand is better than the opponent s hand handname returns a string made up of two parts hand name and high card supported operators rich comparison operators supported builtin methods and functions list sort sorted initialize hand hand should of type str and should contain only five cards each separated by a space the cards should be of the following format card valuecard suit the first character is the value of the card 2 3 4 5 6 7 8 9 ten jack queen king ace the second character represents the suit spades hearts diamonds clubs for example 6s 4c kc as th split removes duplicate whitespaces so no need of strip returns the self hand return self hand def comparewithself other pokerhand str breaking the tie works on the following order of precedence 1 first pair default 0 2 second pair default 0 3 compare all cards in reverse order because they are sorted first pair and second pair will only be a nonzero value if the card type is either from the following 21 four of a kind 20 full house 17 three of a kind 16 two pairs 15 one pair if self handtype other handtype return win elif self handtype other handtype return loss elif self firstpair other firstpair if self secondpair other secondpair return self comparecardsother else return win if self secondpair other secondpair else loss return win if self firstpair other firstpair else loss this function is not part of the problem i did it just for fun def handnameself str name pokerhand handnameself handtype 14 high pokerhand cardnameself highcard pair1 pokerhand cardnameself firstpair pair2 pokerhand cardnameself secondpair if self handtype in 22 19 18 return name f highhigh elif self handtype in 21 17 15 return name f pair1s elif self handtype in 20 16 join over if self handtype 20 else and return name f pair1s join pair2s elif self handtype 23 return name else return name f high def comparecardsself other pokerhand str enumerate gives us the index as well as the element of a list for index cardvalue in enumerateself cardvalues if cardvalue other cardvaluesindex return win if cardvalue other cardvaluesindex else loss return tie def gethandtypeself int number representing the type of hand internally 23 royal flush 22 straight flush 21 four of a kind 20 full house 19 flush 18 straight 17 three of a kind 16 two pairs 15 one pair 14 high card if self isflush if self isfivehighstraight or self isstraight return 23 if sumself cardvalues 60 else 22 return 19 elif self isfivehighstraight or self isstraight return 18 return 14 self issamekind def isflushself bool return lenself cardsuit 1 def isfivehighstraightself bool if a card is a five high straight low ace change the location of ace from the start of the list to the end check whether the first element is ace or not don t want to change again five high straight low ace ah 2h 3s 4c 5d why use sorted here one call to this function will mutate the list to 5 4 3 2 14 and so for subsequent calls which will be rare we need to compare the sorted version refer testmultiplecallsfivehighstraight in testpokerhand py if sortedself cardvalues 2 3 4 5 14 if self cardvalues0 14 remember our list is sorted in reverse order acecard self cardvalues pop0 self cardvalues appendacecard return true return false def isstraightself bool for i in range4 if self cardvaluesi self cardvaluesi 1 1 return false return true def issamekindself int kind values for internal use 7 four of a kind 6 full house 3 three of a kind 2 two pairs 1 one pair 0 false kind val1 val2 0 for i in range4 compare two cards at a time if they are same increase kind add the value of the card to val1 if it is repeating again we will add 2 to kind as there are now 3 cards with same value if we get card of different value than val1 we will do the same thing with val2 if self cardvaluesi self cardvaluesi 1 if not val1 val1 self cardvaluesi kind 1 elif val1 self cardvaluesi kind 2 elif not val2 val2 self cardvaluesi kind 1 elif val2 self cardvaluesi kind 2 for consistency in hand type look at note in gethandtype function kind kind 2 if kind in 4 5 else kind first meaning first pair to compare in comparewith first maxval1 val2 second minval1 val2 if it s full house three count pair two count pair make sure first pair is three count and if not then switch them both if kind 6 and self cardvalues countfirst 3 first second second first self firstpair first self secondpair second return kind def internalstateself tuplelistint setstr internal representation of hand as a list of card values and a set of card suit trans dict t 10 j 11 q 12 k 13 a 14 newhand self hand translatestr maketranstrans split cardvalues intcard 1 for card in newhand cardsuit card1 for card in newhand return sortedcardvalues reversetrue cardsuit def reprself return f self classself hand def strself return self hand rich comparison operators used in list sort and sorted builtin functions note that this is not part of the problem but another extra feature where if you have a list of pokerhand objects you can sort them just through the builtin functions def eqself other if isinstanceother pokerhand return self comparewithother tie return notimplemented def ltself other if isinstanceother pokerhand return self comparewithother loss return notimplemented def leself other if isinstanceother pokerhand return self other or self other return notimplemented def gtself other if isinstanceother pokerhand return not self other and self other return notimplemented def geself other if isinstanceother pokerhand return not self other return notimplemented def hashself return object hashself def solution int solution for problem number 54 from project euler input from pokerhands txt file answer 0 scriptdir os path abspathos path dirnamefile pokerhands os path joinscriptdir pokerhands txt with openpokerhands as filehand for line in filehand playerhand line 14 strip opponenthand line15 strip player opponent pokerhandplayerhand pokerhandopponenthand output player comparewithopponent if output win answer 1 return answer if name main solution create an object representing a poker hand based on an input of a string which represents the best 5 card combination from the player s hand and board cards attributes read only hand a string representing the hand consisting of five cards methods compare_with opponent takes in player s hand self and opponent s hand opponent and compares both hands according to the rules of texas hold em returns one of 3 strings win loss tie based on whether player s hand is better than the opponent s hand hand_name returns a string made up of two parts hand name and high card supported operators rich comparison operators supported built in methods and functions list sort sorted placeholder as tuples are zero indexed initialize hand hand should of type str and should contain only five cards each separated by a space the cards should be of the following format card value card suit the first character is the value of the card 2 3 4 5 6 7 8 9 t en j ack q ueen k ing a ce the second character represents the suit s pades h earts d iamonds c lubs for example 6s 4c kc as th split removes duplicate whitespaces so no need of strip returns the self hand determines the outcome of comparing self hand with other hand returns the output as win loss tie according to the rules of texas hold em here are some examples player pokerhand 2h 3h 4h 5h 6h stright flush opponent pokerhand ks as ts qs js royal flush player compare_with opponent loss player pokerhand 2s ah 2h as ac full house opponent pokerhand 2h 3h 5h 6h 7h flush player compare_with opponent win player pokerhand 2s ah 4h 5s 6c high card opponent pokerhand ad 4c 5h 6h 2c high card player compare_with opponent tie breaking the tie works on the following order of precedence 1 first pair default 0 2 second pair default 0 3 compare all cards in reverse order because they are sorted first pair and second pair will only be a non zero value if the card type is either from the following 21 four of a kind 20 full house 17 three of a kind 16 two pairs 15 one pair this function is not part of the problem i did it just for fun return the name of the hand in the following format hand name high card here are some examples pokerhand ks as ts qs js hand_name royal flush pokerhand 2d 6d 3d 4d 5d hand_name straight flush six high pokerhand jc 6h js jd jh hand_name four of a kind jacks pokerhand 3d 2h 3h 2c 2d hand_name full house twos over threes pokerhand 2h 4d 3c as 5s hand_name low ace straight five high source https en wikipedia org wiki list_of_poker_hands enumerate gives us the index as well as the element of a list number representing the type of hand internally 23 royal flush 22 straight flush 21 four of a kind 20 full house 19 flush 18 straight 17 three of a kind 16 two pairs 15 one pair 14 high card if a card is a five high straight low ace change the location of ace from the start of the list to the end check whether the first element is ace or not don t want to change again five high straight low ace ah 2h 3s 4c 5d why use sorted here one call to this function will mutate the list to 5 4 3 2 14 and so for subsequent calls which will be rare we need to compare the sorted version refer test_multiple_calls_five_high_straight in test_poker_hand py remember our list is sorted in reverse order kind values for internal use 7 four of a kind 6 full house 3 three of a kind 2 two pairs 1 one pair 0 false compare two cards at a time if they are same increase kind add the value of the card to val1 if it is repeating again we will add 2 to kind as there are now 3 cards with same value if we get card of different value than val1 we will do the same thing with val2 for consistency in hand type look at note in _get_hand_type function first meaning first pair to compare in compare_with if it s full house three count pair two count pair make sure first pair is three count and if not then switch them both internal representation of hand as a list of card values and a set of card suit rich comparison operators used in list sort and sorted builtin functions note that this is not part of the problem but another extra feature where if you have a list of pokerhand objects you can sort them just through the builtin functions solution for problem number 54 from project euler input from poker_hands txt file
from __future__ import annotations import os class PokerHand: _HAND_NAME = ( "High card", "One pair", "Two pairs", "Three of a kind", "Straight", "Flush", "Full house", "Four of a kind", "Straight flush", "Royal flush", ) _CARD_NAME = ( "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace", ) def __init__(self, hand: str) -> None: if not isinstance(hand, str): msg = f"Hand should be of type 'str': {hand!r}" raise TypeError(msg) if len(hand.split(" ")) != 5: msg = f"Hand should contain only 5 cards: {hand!r}" raise ValueError(msg) self._hand = hand self._first_pair = 0 self._second_pair = 0 self._card_values, self._card_suit = self._internal_state() self._hand_type = self._get_hand_type() self._high_card = self._card_values[0] @property def hand(self): return self._hand def compare_with(self, other: PokerHand) -> str: if self._hand_type > other._hand_type: return "Win" elif self._hand_type < other._hand_type: return "Loss" elif self._first_pair == other._first_pair: if self._second_pair == other._second_pair: return self._compare_cards(other) else: return "Win" if self._second_pair > other._second_pair else "Loss" return "Win" if self._first_pair > other._first_pair else "Loss" def hand_name(self) -> str: name = PokerHand._HAND_NAME[self._hand_type - 14] high = PokerHand._CARD_NAME[self._high_card] pair1 = PokerHand._CARD_NAME[self._first_pair] pair2 = PokerHand._CARD_NAME[self._second_pair] if self._hand_type in [22, 19, 18]: return name + f", {high}-high" elif self._hand_type in [21, 17, 15]: return name + f", {pair1}s" elif self._hand_type in [20, 16]: join = "over" if self._hand_type == 20 else "and" return name + f", {pair1}s {join} {pair2}s" elif self._hand_type == 23: return name else: return name + f", {high}" def _compare_cards(self, other: PokerHand) -> str: for index, card_value in enumerate(self._card_values): if card_value != other._card_values[index]: return "Win" if card_value > other._card_values[index] else "Loss" return "Tie" def _get_hand_type(self) -> int: if self._is_flush(): if self._is_five_high_straight() or self._is_straight(): return 23 if sum(self._card_values) == 60 else 22 return 19 elif self._is_five_high_straight() or self._is_straight(): return 18 return 14 + self._is_same_kind() def _is_flush(self) -> bool: return len(self._card_suit) == 1 def _is_five_high_straight(self) -> bool: if sorted(self._card_values) == [2, 3, 4, 5, 14]: if self._card_values[0] == 14: ace_card = self._card_values.pop(0) self._card_values.append(ace_card) return True return False def _is_straight(self) -> bool: for i in range(4): if self._card_values[i] - self._card_values[i + 1] != 1: return False return True def _is_same_kind(self) -> int: kind = val1 = val2 = 0 for i in range(4): if self._card_values[i] == self._card_values[i + 1]: if not val1: val1 = self._card_values[i] kind += 1 elif val1 == self._card_values[i]: kind += 2 elif not val2: val2 = self._card_values[i] kind += 1 elif val2 == self._card_values[i]: kind += 2 kind = kind + 2 if kind in [4, 5] else kind first = max(val1, val2) second = min(val1, val2) if kind == 6 and self._card_values.count(first) != 3: first, second = second, first self._first_pair = first self._second_pair = second return kind def _internal_state(self) -> tuple[list[int], set[str]]: trans: dict = {"T": "10", "J": "11", "Q": "12", "K": "13", "A": "14"} new_hand = self._hand.translate(str.maketrans(trans)).split() card_values = [int(card[:-1]) for card in new_hand] card_suit = {card[-1] for card in new_hand} return sorted(card_values, reverse=True), card_suit def __repr__(self): return f'{self.__class__}("{self._hand}")' def __str__(self): return self._hand def __eq__(self, other): if isinstance(other, PokerHand): return self.compare_with(other) == "Tie" return NotImplemented def __lt__(self, other): if isinstance(other, PokerHand): return self.compare_with(other) == "Loss" return NotImplemented def __le__(self, other): if isinstance(other, PokerHand): return self < other or self == other return NotImplemented def __gt__(self, other): if isinstance(other, PokerHand): return not self < other and self != other return NotImplemented def __ge__(self, other): if isinstance(other, PokerHand): return not self < other return NotImplemented def __hash__(self): return object.__hash__(self) def solution() -> int: answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 return answer if __name__ == "__main__": solution()
test that five high straights are compared correctly multiple calls to fivehighstraight function should still return true and shouldn t mutate the list in every call other than the first problem number 54 from project euler testing from pokerhands txt file pair pair pair pair pair pair 2 pairs 2 pairs 2 pairs 2 pairs 3 of a kind 3 of a kind 3 of a kind straight low ace straight straight straight straight high ace flush flush flush flush full house full house full house 4 of a kind 4 of a kind 4 of a kind straight flush low ace straight flush straight flush straight flush royal flush high ace straight flush test that five high straights are compared correctly multiple calls to five_high_straight function should still return true and shouldn t mutate the list in every call other than the first problem number 54 from project euler testing from poker_hands txt file
import os from itertools import chain from random import randrange, shuffle import pytest from .sol1 import PokerHand SORTED_HANDS = ( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS 5S 9S AC", "KD 6S 9D TH AD", "KS 8D 4D 9S 4S", "8C 4S KH JS 4D", "QH 8H KD JH 8S", "KC 4H KS 2H 8D", "KD 4S KC 3H 8S", "AH 8S AS KC JH", "3H 4C 4H 3S 2H", "5S 5D 2C KH KH", "3C KH 5D 5S KH", "AS 3C KH AD KH", "7C 7S 3S 7H 5S", "7C 7S KH 2H 7H", "AC KH QH AH AS", "2H 4D 3C AS 5S", "3C 5C 4C 2C 6H", "6S 8S 7S 5H 9H", "JS QS 9H TS KH", "QC KH TS JS AH", "8C 9C 5C 3C TC", "3S 8S 9S 5S KS", "4C 5C 9C 8C KC", "JH 8H AH KH QH", "3D 2H 3H 2C 2D", "2H 2C 3S 3H 3D", "KH KC 3S 3H 3D", "JC 6H JS JD JH", "JC 7H JS JD JH", "JC KH JS JD JH", "2S AS 4S 5S 3S", "2D 6D 3D 4D 5D", "5C 6C 3C 7C 4C", "JH 9H TH KH QH", "JH AH TH KH QH", ) TEST_COMPARE = ( ("2H 3H 4H 5H 6H", "KS AS TS QS JS", "Loss"), ("2H 3H 4H 5H 6H", "AS AD AC AH JD", "Win"), ("AS AH 2H AD AC", "JS JD JC JH 3D", "Win"), ("2S AH 2H AS AC", "JS JD JC JH AD", "Loss"), ("2S AH 2H AS AC", "2H 3H 5H 6H 7H", "Win"), ("AS 3S 4S 8S 2S", "2H 3H 5H 6H 7H", "Win"), ("2H 3H 5H 6H 7H", "2S 3H 4H 5S 6C", "Win"), ("2S 3H 4H 5S 6C", "3D 4C 5H 6H 2S", "Tie"), ("2S 3H 4H 5S 6C", "AH AC 5H 6H AS", "Win"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H AS", "Loss"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H 7S", "Win"), ("6S AD 7H 4S AS", "AH AC 5H 6H 7S", "Loss"), ("2S AH 4H 5S KC", "AH AC 5H 6H 7S", "Loss"), ("2S 3H 6H 7S 9C", "7H 3C TH 6H 9S", "Loss"), ("4S 5H 6H TS AC", "3S 5H 6H TS AC", "Win"), ("2S AH 4H 5S 6C", "AD 4C 5H 6H 2C", "Tie"), ("AS AH 3H AD AC", "AS AH 2H AD AC", "Win"), ("AH AC 5H 5C QS", "AH AC 5H 5C KS", "Loss"), ("AH AC 5H 5C QS", "KH KC 5H 5C QS", "Win"), ("7C 7S KH 2H 7H", "3C 3S AH 2H 3H", "Win"), ("3C 3S AH 2H 3H", "7C 7S KH 2H 7H", "Loss"), ("6H 5H 4H 3H 2H", "5H 4H 3H 2H AH", "Win"), ("5H 4H 3H 2H AH", "5H 4H 3H 2H AH", "Tie"), ("5H 4H 3H 2H AH", "6H 5H 4H 3H 2H", "Loss"), ("AH AD KS KC AC", "AH KD KH AC KC", "Win"), ("2H 4D 3C AS 5S", "2H 4D 3C 6S 5S", "Loss"), ("2H 3S 3C 3H 2S", "3S 3C 2S 2H 2D", "Win"), ("4D 6D 5D 2D JH", "3S 8S 3H TC KH", "Loss"), ("4S 6C 8S 3S 7S", "AD KS 2D 7D 7C", "Loss"), ("6S 4C 7H 8C 3H", "5H JC AH 9D 9C", "Loss"), ("9D 9H JH TC QH", "3C 2S JS 5C 7H", "Win"), ("2H TC 8S AD 9S", "4H TS 7H 2C 5C", "Win"), ("9D 3S 2C 7S 7C", "JC TD 3C TC 9H", "Loss"), ) TEST_FLUSH = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", True), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", False), ("AS 3S 4S 8S 2S", True), ) TEST_STRAIGHT = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", False), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", True), ) TEST_FIVE_HIGH_STRAIGHT = ( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 14]), ("2H 5D 3C AS 5S", False, [14, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [14, 13, 12, 11, 10]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) TEST_KIND = ( ("JH AH TH KH QH", 0), ("JH 9H TH KH QH", 0), ("JC KH JS JD JH", 7), ("KH KC 3S 3H 3D", 6), ("8C 9C 5C 3C TC", 0), ("JS QS 9H TS KH", 0), ("7C 7S KH 2H 7H", 3), ("3C KH 5D 5S KH", 2), ("QH 8H KD JH 8S", 1), ("2D 6D 9D TH 7D", 0), ) TEST_TYPES = ( ("JH AH TH KH QH", 23), ("JH 9H TH KH QH", 22), ("JC KH JS JD JH", 21), ("KH KC 3S 3H 3D", 20), ("8C 9C 5C 3C TC", 19), ("JS QS 9H TS KH", 18), ("7C 7S KH 2H 7H", 17), ("3C KH 5D 5S KH", 16), ("QH 8H KD JH 8S", 15), ("2D 6D 9D TH 7D", 14), ) def generate_random_hand(): play, oppo = randrange(len(SORTED_HANDS)), randrange(len(SORTED_HANDS)) expected = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] hand, other = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def generate_random_hands(number_of_hands: int = 100): return (generate_random_hand() for _ in range(number_of_hands)) @pytest.mark.parametrize(("hand", "expected"), TEST_FLUSH) def test_hand_is_flush(hand, expected): assert PokerHand(hand)._is_flush() == expected @pytest.mark.parametrize(("hand", "expected"), TEST_STRAIGHT) def test_hand_is_straight(hand, expected): assert PokerHand(hand)._is_straight() == expected @pytest.mark.parametrize(("hand", "expected", "card_values"), TEST_FIVE_HIGH_STRAIGHT) def test_hand_is_five_high_straight(hand, expected, card_values): player = PokerHand(hand) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize(("hand", "expected"), TEST_KIND) def test_hand_is_same_kind(hand, expected): assert PokerHand(hand)._is_same_kind() == expected @pytest.mark.parametrize(("hand", "expected"), TEST_TYPES) def test_hand_values(hand, expected): assert PokerHand(hand)._hand_type == expected @pytest.mark.parametrize(("hand", "other", "expected"), TEST_COMPARE) def test_compare_simple(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected @pytest.mark.parametrize(("hand", "other", "expected"), generate_random_hands()) def test_compare_random(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected def test_hand_sorted(): poker_hands = [PokerHand(hand) for hand in SORTED_HANDS] list_copy = poker_hands.copy() shuffle(list_copy) user_sorted = chain(sorted(list_copy)) for index, hand in enumerate(user_sorted): assert hand == poker_hands[index] def test_custom_sort_five_high_straight(): pokerhands = [PokerHand("2D AC 3H 4H 5S"), PokerHand("2S 3H 4H 5S 6C")] pokerhands.sort(reverse=True) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def test_multiple_calls_five_high_straight(): pokerhand = PokerHand("2C 4S AS 3D 5C") expected = True expected_card_values = [5, 4, 3, 2, 14] for _ in range(10): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def test_euler_project(): answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 assert answer == 376
lychrel numbers problem 55 https projecteuler netproblem55 if we take 47 reverse and add 47 74 121 which is palindromic not all numbers produce palindromes so quickly for example 349 943 1292 1292 2921 4213 4213 3124 7337 that is 349 took three iterations to arrive at a palindrome although no one has proved it yet it is thought that some numbers like 196 never produce a palindrome a number that never forms a palindrome through the reverse and add process is called a lychrel number due to the theoretical nature of these numbers and for the purpose of this problem we shall assume that a number is lychrel until proven otherwise in addition you are given that for every number below tenthousand it will either i become a palindrome in less than fifty iterations or ii no one with all the computing power that exists has managed so far to map it to a palindrome in fact 10677 is the first number to be shown to require over fifty iterations before producing a palindrome 4668731596684224866951378664 53 iterations 28digits surprisingly there are palindromic numbers that are themselves lychrel numbers the first example is 4994 how many lychrel numbers are there below tenthousand returns true if a number is palindrome ispalindrome12567321 false ispalindrome1221 true ispalindrome9876789 true returns the sum of n and reverse of n sumreverse123 444 sumreverse3478 12221 sumreverse12 33 returns the count of all lychrel numbers below limit solution10000 249 solution5000 76 solution1000 13 returns true if a number is palindrome is_palindrome 12567321 false is_palindrome 1221 true is_palindrome 9876789 true returns the sum of n and reverse of n sum_reverse 123 444 sum_reverse 3478 12221 sum_reverse 12 33 returns the count of all lychrel numbers below limit solution 10000 249 solution 5000 76 solution 1000 13
def is_palindrome(n: int) -> bool: return str(n) == str(n)[::-1] def sum_reverse(n: int) -> int: return int(n) + int(str(n)[::-1]) def solution(limit: int = 10000) -> int: lychrel_nums = [] for num in range(1, limit): iterations = 0 a = num while iterations < 50: num = sum_reverse(num) iterations += 1 if is_palindrome(num): break else: lychrel_nums.append(a) return len(lychrel_nums) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 56 https projecteuler netproblem56 a googol 10100 is a massive number one followed by onehundred zeros 100100 is almost unimaginably large one followed by twohundred zeros despite their size the sum of the digits in each number is only 1 considering natural numbers of the form ab where a b 100 what is the maximum digital sum considering natural numbers of the form ab where a b 100 what is the maximum digital sum param a param b return solution10 10 45 solution100 100 972 solution100 200 1872 return the maximum from the list of sums of the list of int converted from str of base raised to the power tests considering natural numbers of the form a b where a b 100 what is the maximum digital sum param a param b return solution 10 10 45 solution 100 100 972 solution 100 200 1872 return the maximum from the list of sums of the list of int converted from str of base raised to the power tests
def solution(a: int = 100, b: int = 100) -> int: return max( sum(int(x) for x in str(base**power)) for base in range(a) for power in range(b) ) if __name__ == "__main__": import doctest doctest.testmod()
project euler problem 57 https projecteuler netproblem57 it is possible to show that the square root of two can be expressed as an infinite continued fraction sqrt2 1 1 2 1 2 1 2 by expanding this for the first four iterations we get 1 1 2 3 2 1 5 1 1 2 1 2 7 5 1 4 1 1 2 1 2 1 2 17 12 1 41666 1 1 2 1 2 1 2 1 2 41 29 1 41379 the next three expansions are 9970 239169 and 577408 but the eighth expansion 1393985 is the first example where the number of digits in the numerator exceeds the number of digits in the denominator in the first onethousand expansions how many fractions contain a numerator with more digits than the denominator returns number of fractions containing a numerator with more digits than the denominator in the first n expansions solution14 2 solution100 15 solution10000 1508 returns number of fractions containing a numerator with more digits than the denominator in the first n expansions solution 14 2 solution 100 15 solution 10000 1508
def solution(n: int = 1000) -> int: prev_numerator, prev_denominator = 1, 1 result = [] for i in range(1, n + 1): numerator = prev_numerator + 2 * prev_denominator denominator = prev_numerator + prev_denominator if len(str(numerator)) > len(str(denominator)): result.append(i) prev_numerator = numerator prev_denominator = denominator return len(result) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 58 https projecteuler netproblem58 starting with 1 and spiralling anticlockwise in the following way a square spiral with side length 7 is formed 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 it is interesting to note that the odd squares lie along the bottom right diagonal but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime that is a ratio of 813 62 if one complete new layer is wrapped around the spiral above a square spiral with side length 9 will be formed if this process is continued what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10 solution we have to find an odd length side for which square falls below 10 with every layer we add 4 elements are being added to the diagonals lets say we have a square spiral of odd length with side length j then if we move from j to j2 we are adding jjj1 jj2j1 jj3j1 jj4j1 out of these 4 only the first three can become prime because last one reduces to j2j2 so we check individually each one of these before incrementing our count of current primes checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself isprime0 false isprime1 false isprime2 true isprime3 true isprime27 false isprime87 false isprime563 true isprime2999 true isprime67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio solution 5 11 solution 2 309 solution 111 11317 checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself is_prime 0 false is_prime 1 false is_prime 2 true is_prime 3 true is_prime 27 false is_prime 87 false is_prime 563 true is_prime 2999 true is_prime 67483 false 2 and 3 are primes negatives 0 1 all even numbers all multiples of 3 are not primes all primes number are in format of 6k 1 returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio solution 5 11 solution 2 309 solution 111 11317
import math def is_prime(number: int) -> bool: if 1 < number < 4: return True elif number < 2 or number % 2 == 0 or number % 3 == 0: return False for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(ratio: float = 0.1) -> int: j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes += is_prime(i) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
each character on a computer is assigned a unique code and the preferred standard is ascii american standard code for information interchange for example uppercase a 65 asterisk 42 and lowercase k 107 a modern encryption method is to take a text file convert the bytes to ascii then xor each byte with a given value taken from a secret key the advantage with the xor function is that using the same encryption key on the cipher text restores the plain text for example 65 xor 42 107 then 107 xor 42 65 for unbreakable encryption the key is the same length as the plain text message and the key is made up of random bytes the user would keep the encrypted message and the encryption key in different locations and without both halves it is impossible to decrypt the message unfortunately this method is impractical for most users so the modified method is to use a password as a key if the password is shorter than the message which is likely the key is repeated cyclically throughout the message the balance for this method is using a sufficiently long password key for security but short enough to be memorable your task has been made easy as the encryption key consists of three lower case characters using p059cipher txt right click and save linktarget as a file containing the encrypted ascii codes and the knowledge that the plain text must contain common english words decrypt the message and find the sum of the ascii values in the original text given an encrypted message and a possible 3character key decrypt the message if the decrypted message contains a invalid character i e not an ascii letter a digit punctuation or whitespace then we know the key is incorrect so return none trykey0 17 20 4 27 104 116 120 hello trykey68 10 300 4 27 104 116 120 is none true given an encrypted message test all 3character strings to try and find the key return a list of the possible decrypted messages from itertools import cycle text the enemy s gate is down key end encoded ordk ordc for k c in zipcyclekey text text in filtervalidcharsencoded true given a list of possible decoded messages narrow down the possibilities for checking for the presence of a specified common word only decoded messages containing commonword will be returned filtercommonword asfla adf i am here a am i am here filtercommonword athla amf i am here a am athla amf i am here test the ciphertext against all possible 3character keys then narrow down the possibilities by filtering using common words until there s only one possible decoded message solutiontestcipher txt 3000 given an encrypted message and a possible 3 character key decrypt the message if the decrypted message contains a invalid character i e not an ascii letter a digit punctuation or whitespace then we know the key is incorrect so return none try_key 0 17 20 4 27 104 116 120 hello try_key 68 10 300 4 27 104 116 120 is none true given an encrypted message test all 3 character strings to try and find the key return a list of the possible decrypted messages from itertools import cycle text the enemy s gate is down key end encoded ord k ord c for k c in zip cycle key text text in filter_valid_chars encoded true given a list of possible decoded messages narrow down the possibilities for checking for the presence of a specified common word only decoded messages containing common_word will be returned filter_common_word asfla adf i am here a am i am here filter_common_word athla amf i am here a am athla amf i am here test the ciphertext against all possible 3 character keys then narrow down the possibilities by filtering using common words until there s only one possible decoded message solution test_cipher txt 3000
from __future__ import annotations import string from itertools import cycle, product from pathlib import Path VALID_CHARS: str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) LOWERCASE_INTS: list[int] = [ord(letter) for letter in string.ascii_lowercase] VALID_INTS: set[int] = {ord(char) for char in VALID_CHARS} COMMON_WORDS: list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"] def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None: decoded: str = "" keychar: int cipherchar: int decodedchar: int for keychar, cipherchar in zip(cycle(key), ciphertext): decodedchar = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(decodedchar) return decoded def filter_valid_chars(ciphertext: list[int]) -> list[str]: possibles: list[str] = [] for key in product(LOWERCASE_INTS, repeat=3): encoded = try_key(ciphertext, key) if encoded is not None: possibles.append(encoded) return possibles def filter_common_word(possibles: list[str], common_word: str) -> list[str]: return [possible for possible in possibles if common_word in possible.lower()] def solution(filename: str = "p059_cipher.txt") -> int: ciphertext: list[int] possibles: list[str] common_word: str decoded_text: str data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") ciphertext = [int(number) for number in data.strip().split(",")] possibles = filter_valid_chars(ciphertext) for common_word in COMMON_WORDS: possibles = filter_common_word(possibles, common_word) if len(possibles) == 1: break decoded_text = possibles[0] return sum(ord(char) for char in decoded_text) if __name__ == "__main__": print(f"{solution() = }")
project euler 62 https projecteuler netproblem62 the cube 41063625 3453 can be permuted to produce two other cubes 56623104 3843 and 66430125 4053 in fact 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube find the smallest cube for which exactly five permutations of its digits are cube iterate through every possible cube and sort the cube s digits in ascending order sorting maintains an ordering of the digits that allows you to compare permutations store each sorted sequence of digits in a dictionary whose key is the sequence of digits and value is a list of numbers that are the base of the cube once you find 5 numbers that produce the same sequence of digits return the smallest one which is at index 0 since we insert each base number in ascending order solution2 125 solution3 41063625 computes the sorted sequence of digits of the cube of num getdigits3 27 getdigits99 027999 getdigits123 0166788 iterate through every possible cube and sort the cube s digits in ascending order sorting maintains an ordering of the digits that allows you to compare permutations store each sorted sequence of digits in a dictionary whose key is the sequence of digits and value is a list of numbers that are the base of the cube once you find 5 numbers that produce the same sequence of digits return the smallest one which is at index 0 since we insert each base number in ascending order solution 2 125 solution 3 41063625 computes the sorted sequence of digits of the cube of num get_digits 3 27 get_digits 99 027999 get_digits 123 0166788
from collections import defaultdict def solution(max_base: int = 5) -> int: freqs = defaultdict(list) num = 0 while True: digits = get_digits(num) freqs[digits].append(num) if len(freqs[digits]) == max_base: base = freqs[digits][0] ** 3 return base num += 1 def get_digits(num: int) -> str: return "".join(sorted(str(num**3))) if __name__ == "__main__": print(f"{solution() = }")
the 5digit number 1680775 is also a fifth power similarly the 9digit number 13421772889 is a ninth power how many ndigit positive integers exist which are also an nth power the maximum base can be 9 because all ndigit numbers 10n now 923 has 22 digits so the maximum power can be 22 using these conclusions we will calculate the result returns the count of all ndigit numbers which are nth power solution10 22 49 solution0 0 0 solution1 1 0 solution1 1 0 the maximum base can be 9 because all n digit numbers 10 n now 9 23 has 22 digits so the maximum power can be 22 using these conclusions we will calculate the result returns the count of all n digit numbers which are nth power solution 10 22 49 solution 0 0 0 solution 1 1 0 solution 1 1 0
def solution(max_base: int = 10, max_power: int = 22) -> int: bases = range(1, max_base) powers = range(1, max_power) return sum( 1 for power in powers for base in bases if len(str(base**power)) == power ) if __name__ == "__main__": print(f"{solution(10, 22) = }")
project euler problem 64 https projecteuler netproblem64 all square roots are periodic when written as continued fractions for example let us consider sqrt23 it can be seen that the sequence is repeating for conciseness we use the notation sqrt234 1 3 1 8 to indicate that the block 1 3 1 8 repeats indefinitely exactly four continued fractions for n13 have an odd period how many continued fractions for n10000 have an odd period references https en wikipedia orgwikicontinuedfraction returns the continued fraction period of a number n continuousfractionperiod2 1 continuousfractionperiod5 1 continuousfractionperiod7 4 continuousfractionperiod11 2 continuousfractionperiod13 5 returns the count of numbers 10000 with odd periods this function calls continuousfractionperiod for numbers which are not perfect squares this is checked in if sr floorsr 0 statement if an odd period is returned by continuousfractionperiod countoddperiods is increased by 1 solution2 1 solution5 2 solution7 2 solution11 3 solution13 4 returns the continued fraction period of a number n continuous_fraction_period 2 1 continuous_fraction_period 5 1 continuous_fraction_period 7 4 continuous_fraction_period 11 2 continuous_fraction_period 13 5 returns the count of numbers 10000 with odd periods this function calls continuous_fraction_period for numbers which are not perfect squares this is checked in if sr floor sr 0 statement if an odd period is returned by continuous_fraction_period count_odd_periods is increased by 1 solution 2 1 solution 5 2 solution 7 2 solution 11 3 solution 13 4
from math import floor, sqrt def continuous_fraction_period(n: int) -> int: numerator = 0.0 denominator = 1.0 root = int(sqrt(n)) integer_part = root period = 0 while integer_part != 2 * root: numerator = denominator * integer_part - numerator denominator = (n - numerator**2) / denominator integer_part = int((root + numerator) / denominator) period += 1 return period def solution(n: int = 10000) -> int: count_odd_periods = 0 for i in range(2, n + 1): sr = sqrt(i) if sr - floor(sr) != 0 and continuous_fraction_period(i) % 2 == 1: count_odd_periods += 1 return count_odd_periods if __name__ == "__main__": print(f"{solution(int(input().strip()))}")
project euler problem 65 https projecteuler netproblem65 the square root of 2 can be written as an infinite continued fraction sqrt2 1 1 2 1 2 1 2 1 2 the infinite continued fraction can be written sqrt2 1 2 2 indicates that 2 repeats ad infinitum in a similar way sqrt23 4 1 3 1 8 it turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations let us consider the convergents for sqrt2 1 1 2 32 1 1 2 1 2 75 1 1 2 1 2 1 2 1712 1 1 2 1 2 1 2 1 2 4129 hence the sequence of the first ten convergents for sqrt2 are 1 32 75 1712 4129 9970 239169 577408 1393985 33632378 what is most surprising is that the important mathematical constant e 2 1 2 1 1 4 1 1 6 1 1 2k 1 the first ten terms in the sequence of convergents for e are 2 3 83 114 197 8732 10639 19371 1264465 1457536 the sum of digits in the numerator of the 10th convergent is 1 4 5 7 17 find the sum of the digits in the numerator of the 100th convergent of the continued fraction for e the solution mostly comes down to finding an equation that will generate the numerator of the continued fraction for the ith numerator the pattern is ni mi ni1 ni2 for mi the ith index of the continued fraction representation of e n0 1 and n1 2 as the first 2 numbers of the representation for example n9 6 193 106 1264 1 2 6 4 13 n10 1 193 1264 1457 1 4 5 7 17 returns the sum of every digit in num sumdigits1 1 sumdigits12345 15 sumdigits999001 28 returns the sum of the digits in the numerator of the maxth convergent of the continued fraction for e solution9 13 solution10 17 solution50 91 returns the sum of every digit in num sum_digits 1 1 sum_digits 12345 15 sum_digits 999001 28 returns the sum of the digits in the numerator of the max th convergent of the continued fraction for e solution 9 13 solution 10 17 solution 50 91
def sum_digits(num: int) -> int: digit_sum = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def solution(max_n: int = 100) -> int: pre_numerator = 1 cur_numerator = 2 for i in range(2, max_n + 1): temp = pre_numerator e_cont = 2 * i // 3 if i % 3 == 0 else 1 pre_numerator = cur_numerator cur_numerator = e_cont * pre_numerator + temp return sum_digits(cur_numerator) if __name__ == "__main__": print(f"{solution() = }")
problem statement by starting at the top of the triangle below and moving to adjacent numbers on the row below the maximum total from top to bottom is 23 3 7 4 2 4 6 8 5 9 3 that is 3 7 4 9 23 find the maximum total from top to bottom in triangle txt right click and save linktarget as a 15k text file containing a triangle with onehundred rows finds the maximum total in a triangle as described by the problem statement above solution 7273 finds the maximum total in a triangle as described by the problem statement above solution 7273
import os def solution(): script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") with open(triangle) as f: triangle = f.readlines() a = [] for line in triangle: numbers_from_line = [] for number in line.strip().split(" "): numbers_from_line.append(int(number)) a.append(numbers_from_line) for i in range(1, len(a)): for j in range(len(a[i])): number1 = a[i - 1][j] if j != len(a[i - 1]) else 0 number2 = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(number1, number2) return max(a[-1]) if __name__ == "__main__": print(solution())
problem statement by starting at the top of the triangle below and moving to adjacent numbers on the row below the maximum total from top to bottom is 23 3 7 4 2 4 6 8 5 9 3 that is 3 7 4 9 23 find the maximum total from top to bottom in triangle txt right click and save linktarget as a 15k text file containing a triangle with onehundred rows finds the maximum total in a triangle as described by the problem statement above solution 7273 finds the maximum total in a triangle as described by the problem statement above solution 7273
import os def solution() -> int: script_dir = os.path.dirname(os.path.realpath(__file__)) triangle_path = os.path.join(script_dir, "triangle.txt") with open(triangle_path) as in_file: triangle = [[int(i) for i in line.split()] for line in in_file] while len(triangle) != 1: last_row = triangle.pop() curr_row = triangle[-1] for j in range(len(last_row) - 1): curr_row[j] += max(last_row[j], last_row[j + 1]) return triangle[0][0] if __name__ == "__main__": print(solution())
project euler problem 68 https projecteuler netproblem68 magic 5gon ring problem statement consider the following magic 3gon ring filled with the numbers 1 to 6 and each line adding to nine 4 3 1 2 6 5 working clockwise and starting from the group of three with the numerically lowest external node 4 3 2 in this example each solution can be described uniquely for example the above solution can be described by the set 4 3 2 6 2 1 5 1 3 it is possible to complete the ring with four different totals 9 10 11 and 12 there are eight solutions in total total solution set 9 4 2 3 5 3 1 6 1 2 9 4 3 2 6 2 1 5 1 3 10 2 3 5 4 5 1 6 1 3 10 2 5 3 6 3 1 4 1 5 11 1 4 6 3 6 2 5 2 4 11 1 6 4 5 4 2 3 2 6 12 1 5 6 2 6 4 3 4 5 12 1 6 5 3 5 4 2 4 6 by concatenating each group it is possible to form 9digit strings the maximum string for a 3gon ring is 432621513 using the numbers 1 to 10 and depending on arrangements it is possible to form 16 and 17digit strings what is the maximum 16digit string for a magic 5gon ring find the maximum number for a magic gonsidegon ring the gonside parameter should be in the range 3 5 other side numbers aren t tested solution3 432621513 solution4 426561813732 solution 6531031914842725 solution6 traceback most recent call last valueerror gonside must be in the range 3 5 since it s 16 we know 10 is on the outer ring put the big numbers at the end so that they are never the first number generate a gonsidegon ring from a permutation state the permutation state is the ring but every duplicate is removed generategonring3 4 2 3 5 1 6 4 2 3 5 3 1 6 1 2 generategonring5 6 5 4 3 2 1 7 8 9 10 6 5 4 3 4 2 1 2 7 8 7 9 10 9 5 check if the solution set is a magic ngon ring check that the first number is the smallest number on the outer ring take a list and check if the sum of each 3 numbers chunk is equal to the same total ismagicgon4 2 3 5 3 1 6 1 2 true ismagicgon4 3 2 6 2 1 5 1 3 true ismagicgon2 3 5 4 5 1 6 1 3 true ismagicgon1 2 3 4 5 6 7 8 9 false ismagicgon1 traceback most recent call last valueerror a gon ring should have a length that is a multiple of 3 find the maximum number for a magic gon_side gon ring the gon_side parameter should be in the range 3 5 other side numbers aren t tested solution 3 432621513 solution 4 426561813732 solution 6531031914842725 solution 6 traceback most recent call last valueerror gon_side must be in the range 3 5 since it s 16 we know 10 is on the outer ring put the big numbers at the end so that they are never the first number generate a gon_side gon ring from a permutation state the permutation state is the ring but every duplicate is removed generate_gon_ring 3 4 2 3 5 1 6 4 2 3 5 3 1 6 1 2 generate_gon_ring 5 6 5 4 3 2 1 7 8 9 10 6 5 4 3 4 2 1 2 7 8 7 9 10 9 5 check if the solution set is a magic n gon ring check that the first number is the smallest number on the outer ring take a list and check if the sum of each 3 numbers chunk is equal to the same total is_magic_gon 4 2 3 5 3 1 6 1 2 true is_magic_gon 4 3 2 6 2 1 5 1 3 true is_magic_gon 2 3 5 4 5 1 6 1 3 true is_magic_gon 1 2 3 4 5 6 7 8 9 false is_magic_gon 1 traceback most recent call last valueerror a gon ring should have a length that is a multiple of 3
from itertools import permutations def solution(gon_side: int = 5) -> int: if gon_side < 3 or gon_side > 5: raise ValueError("gon_side must be in the range [3, 5]") small_numbers = list(range(gon_side + 1, 0, -1)) big_numbers = list(range(gon_side + 2, gon_side * 2 + 1)) for perm in permutations(small_numbers + big_numbers): numbers = generate_gon_ring(gon_side, list(perm)) if is_magic_gon(numbers): return int("".join(str(n) for n in numbers)) msg = f"Magic {gon_side}-gon ring is impossible" raise ValueError(msg) def generate_gon_ring(gon_side: int, perm: list[int]) -> list[int]: result = [0] * (gon_side * 3) result[0:3] = perm[0:3] perm.append(perm[1]) magic_number = 1 if gon_side < 5 else 2 for i in range(1, len(perm) // 3 + magic_number): result[3 * i] = perm[2 * i + 1] result[3 * i + 1] = result[3 * i - 1] result[3 * i + 2] = perm[2 * i + 2] return result def is_magic_gon(numbers: list[int]) -> bool: if len(numbers) % 3 != 0: raise ValueError("a gon ring should have a length that is a multiple of 3") if min(numbers[::3]) != numbers[0]: return False total = sum(numbers[:3]) return all(sum(numbers[i : i + 3]) == total for i in range(3, len(numbers), 3)) if __name__ == "__main__": print(solution())
totient maximum problem 69 https projecteuler netproblem69 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 96 n relatively prime n nn 2 1 1 2 3 1 2 2 1 5 4 1 3 2 2 5 1 2 3 4 4 1 25 6 1 5 2 3 7 1 2 3 4 5 6 6 1 1666 8 1 3 5 7 4 2 9 1 2 4 5 7 8 6 1 5 10 1 3 7 9 4 2 5 it can be seen that n6 produces a maximum nn for n 10 find the value of n 1 000 000 for which nn is a maximum returns solution to problem algorithm 1 precompute k for all natural k k n using product formula wikilink below https en wikipedia orgwikieuler27stotientfunctioneuler sproductformula 2 find kk for all k n and return the k that attains maximum solution10 6 solution100 30 solution9973 2310 returns solution to problem algorithm 1 precompute φ k for all natural k k n using product formula wikilink below https en wikipedia org wiki euler 27s_totient_function euler s_product_formula 2 find k φ k for all k n and return the k that attains maximum solution 10 6 solution 100 30 solution 9973 2310
def solution(n: int = 10**6) -> int: if n <= 0: raise ValueError("Please enter an integer greater than 0") phi = list(range(n + 1)) for number in range(2, n + 1): if phi[number] == number: phi[number] -= 1 for multiple in range(number * 2, n + 1, number): phi[multiple] = (phi[multiple] // number) * (number - 1) answer = 1 for number in range(1, n + 1): if (answer / phi[answer]) < (number / phi[number]): answer = number return answer if __name__ == "__main__": print(solution())
project euler problem 70 https projecteuler netproblem70 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 relatively prime to nine 96 the number 1 is considered to be relatively prime to every positive number so 11 interestingly 8710979180 and it can be seen that 87109 is a permutation of 79180 find the value of n 1 n 107 for which n is a permutation of n and the ratio nn produces a minimum this is essentially brute force calculate all totients up to 107 and find the minimum ratio of nn that way to minimize the ratio we want to minimize n and maximize n as much as possible so we can store the minimum fraction s numerator and denominator and calculate new fractions with each totient to compare against to avoid dividing by zero i opt to use cross multiplication references finding totients https en wikipedia orgwikieuler stotientfunctioneuler sproductformula calculates a list of totients from 0 to maxone exclusive using the definition of euler s product formula gettotients5 0 1 1 2 2 gettotients10 0 1 1 2 2 4 2 6 4 6 return true if num1 and num2 have the same frequency of every digit false otherwise hassamedigits123456789 987654321 true hassamedigits123 23 false hassamedigits1234566 123456 false finds the value of n from 1 to max such that nn produces a minimum solution100 21 solution10000 4435 calculates a list of totients from 0 to max_one exclusive using the definition of euler s product formula get_totients 5 0 1 1 2 2 get_totients 10 0 1 1 2 2 4 2 6 4 6 array of indexes to select return true if num1 and num2 have the same frequency of every digit false otherwise has_same_digits 123456789 987654321 true has_same_digits 123 23 false has_same_digits 1234566 123456 false finds the value of n from 1 to max such that n φ n produces a minimum solution 100 21 solution 10000 4435 i φ i
from __future__ import annotations import numpy as np def get_totients(max_one: int) -> list[int]: totients = np.arange(max_one) for i in range(2, max_one): if totients[i] == i: x = np.arange(i, max_one, i) totients[x] -= totients[x] // i return totients.tolist() def has_same_digits(num1: int, num2: int) -> bool: return sorted(str(num1)) == sorted(str(num2)) def solution(max_n: int = 10000000) -> int: min_numerator = 1 min_denominator = 0 totients = get_totients(max_n + 1) for i in range(2, max_n + 1): t = totients[i] if i * min_denominator < min_numerator * t and has_same_digits(i, t): min_numerator = i min_denominator = t return min_numerator if __name__ == "__main__": print(f"{solution() = }")
ordered fractions problem 71 https projecteuler netproblem71 consider the fraction nd where n and d are positive integers if nd and hcfn d1 it is called a reduced proper fraction if we list the set of reduced proper fractions for d 8 in ascending order of size we get 18 17 16 15 14 27 13 38 25 37 12 47 35 58 23 57 34 45 56 67 78 it can be seen that 25 is the fraction immediately to the left of 37 by listing the set of reduced proper fractions for d 1 000 000 in ascending order of size find the numerator of the fraction immediately to the left of 37 returns the closest numerator of the fraction immediately to the left of given fraction numeratordenominator from a list of reduced proper fractions solution 428570 solution3 7 8 2 solution6 7 60 47 returns the closest numerator of the fraction immediately to the left of given fraction numerator denominator from a list of reduced proper fractions solution 428570 solution 3 7 8 2 solution 6 7 60 47
def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
problem 72 counting fractions https projecteuler netproblem72 description consider the fraction nd where n and d are positive integers if nd and hcfn d1 it is called a reduced proper fraction if we list the set of reduced proper fractions for d 8 in ascending order of size we get 18 17 16 15 14 27 13 38 25 37 12 47 35 58 23 57 34 45 56 67 78 it can be seen that there are 21 elements in this set how many elements would be contained in the set of reduced proper fractions for d 1 000 000 solution number of numbers between 1 and n that are coprime to n is given by the euler s totient function phin so the answer is simply the sum of phin for 2 n 1 000 000 sum of phid for all dn n this result can be used to find phin using a sieve time 1 sec returns an integer the solution to the problem solution10 31 solution100 3043 solution1000 304191 generating an array from 1 to limit returns an integer the solution to the problem solution 10 31 solution 100 3043 solution 1_000 304191 generating an array from 1 to limit indexes for selection
import numpy as np def solution(limit: int = 1_000_000) -> int: phi = np.arange(-1, limit) for i in range(2, limit + 1): if phi[i] == i - 1: ind = np.arange(2 * i, limit + 1, i) phi[ind] -= phi[ind] // i return np.sum(phi[2 : limit + 1]) if __name__ == "__main__": print(solution())
project euler problem 72 https projecteuler netproblem72 consider the fraction nd where n and d are positive integers if nd and hcfn d1 it is called a reduced proper fraction if we list the set of reduced proper fractions for d 8 in ascending order of size we get 18 17 16 15 14 27 13 38 25 37 12 47 35 58 23 57 34 45 56 67 78 it can be seen that there are 21 elements in this set how many elements would be contained in the set of reduced proper fractions for d 1 000 000 return the number of reduced proper fractions with denominator less than limit solution8 21 solution1000 304191 return the number of reduced proper fractions with denominator less than limit solution 8 21 solution 1000 304191
def solution(limit: int = 1000000) -> int: primes = set(range(3, limit, 2)) primes.add(2) for p in range(3, limit, 2): if p not in primes: continue primes.difference_update(set(range(p * p, limit, p))) phi = [float(n) for n in range(limit + 1)] for p in primes: for n in range(p, limit + 1, p): phi[n] *= 1 - 1 / p return int(sum(phi[2:])) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 73 https projecteuler netproblem73 consider the fraction nd where n and d are positive integers if nd and hcfn d1 it is called a reduced proper fraction if we list the set of reduced proper fractions for d 8 in ascending order of size we get 18 17 16 15 14 27 13 38 25 37 12 47 35 58 23 57 34 45 56 67 78 it can be seen that there are 3 fractions between 13 and 12 how many fractions lie between 13 and 12 in the sorted set of reduced proper fractions for d 12 000 returns number of fractions lie between 13 and 12 in the sorted set of reduced proper fractions for d maxd solution4 0 solution5 1 solution8 3 returns number of fractions lie between 1 3 and 1 2 in the sorted set of reduced proper fractions for d max_d solution 4 0 solution 5 1 solution 8 3
from math import gcd def solution(max_d: int = 12_000) -> int: fractions_number = 0 for d in range(max_d + 1): for n in range(d // 3 + 1, (d + 1) // 2): if gcd(n, d) == 1: fractions_number += 1 return fractions_number if __name__ == "__main__": print(f"{solution() = }")
project euler problem 74 https projecteuler netproblem74 the number 145 is well known for the property that the sum of the factorial of its digits is equal to 145 1 4 5 1 24 120 145 perhaps less well known is 169 in that it produces the longest chain of numbers that link back to 169 it turns out that there are only three such loops that exist 169 363601 1454 169 871 45361 871 872 45362 872 it is not difficult to prove that every starting number will eventually get stuck in a loop for example 69 363600 1454 169 363601 1454 78 45360 871 45361 871 540 145 145 starting with 69 produces a chain of five nonrepeating terms but the longest nonrepeating chain with a starting number below one million is sixty terms how many chains with a starting number below one million contain exactly sixty nonrepeating terms return the sum of the factorial of the digits of n sumdigitfactorials145 145 sumdigitfactorials45361 871 sumdigitfactorials540 145 calculate the length of the chain of nonrepeating terms starting with n previous is a set containing the previous member of the chain chainlength10101 11 chainlength555 20 chainlength178924 39 return the number of chains with a starting number below one million which contain exactly n nonrepeating terms solution10 1000 28 return the sum of the factorial of the digits of n sum_digit_factorials 145 145 sum_digit_factorials 45361 871 sum_digit_factorials 540 145 calculate the length of the chain of non repeating terms starting with n previous is a set containing the previous member of the chain chain_length 10101 11 chain_length 555 20 chain_length 178924 39 return the number of chains with a starting number below one million which contain exactly n non repeating terms solution 10 1000 28
DIGIT_FACTORIALS = { "0": 1, "1": 1, "2": 2, "3": 6, "4": 24, "5": 120, "6": 720, "7": 5040, "8": 40320, "9": 362880, } CACHE_SUM_DIGIT_FACTORIALS = {145: 145} CHAIN_LENGTH_CACHE = { 145: 0, 169: 3, 36301: 3, 1454: 3, 871: 2, 45361: 2, 872: 2, } def sum_digit_factorials(n: int) -> int: if n in CACHE_SUM_DIGIT_FACTORIALS: return CACHE_SUM_DIGIT_FACTORIALS[n] ret = sum(DIGIT_FACTORIALS[let] for let in str(n)) CACHE_SUM_DIGIT_FACTORIALS[n] = ret return ret def chain_length(n: int, previous: set | None = None) -> int: previous = previous or set() if n in CHAIN_LENGTH_CACHE: return CHAIN_LENGTH_CACHE[n] next_number = sum_digit_factorials(n) if next_number in previous: CHAIN_LENGTH_CACHE[n] = 0 return 0 else: previous.add(n) ret = 1 + chain_length(next_number, previous) CHAIN_LENGTH_CACHE[n] = ret return ret def solution(num_terms: int = 60, max_start: int = 1000000) -> int: return sum(1 for i in range(1, max_start) if chain_length(i) == num_terms) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 074 https projecteuler netproblem74 the number 145 is well known for the property that the sum of the factorial of its digits is equal to 145 1 4 5 1 24 120 145 perhaps less well known is 169 in that it produces the longest chain of numbers that link back to 169 it turns out that there are only three such loops that exist 169 363601 1454 169 871 45361 871 872 45362 872 it is not difficult to prove that every starting number will eventually get stuck in a loop for example 69 363600 1454 169 363601 1454 78 45360 871 45361 871 540 145 145 starting with 69 produces a chain of five nonrepeating terms but the longest nonrepeating chain with a starting number below one million is sixty terms how many chains with a starting number below one million contain exactly sixty nonrepeating terms solution approach this solution simply consists in a loop that generates the chains of non repeating items using the cached sizes of the previous chains the generation of the chain stops before a repeating item or if the size of the chain is greater then the desired one after generating each chain the length is checked and the counter increases function to perform the sum of the factorial of all the digits in number digitfactorialsum69 0 traceback most recent call last typeerror parameter number must be int digitfactorialsum1 traceback most recent call last valueerror parameter number must be greater than or equal to 0 digitfactorialsum0 1 digitfactorialsum69 363600 converts number in string to iterate on its digits and adds its factorial returns the number of numbers below numberlimit that produce chains with exactly chainlength non repeating elements solution10 0 1000 traceback most recent call last typeerror parameters chainlength and numberlimit must be int solution10 1000 0 traceback most recent call last typeerror parameters chainlength and numberlimit must be int solution0 1000 traceback most recent call last valueerror parameters chainlength and numberlimit must be greater than 0 solution10 0 traceback most recent call last valueerror parameters chainlength and numberlimit must be greater than 0 solution10 1000 26 the counter for the chains with the exact desired length the cached sizes of the previous chains the temporary set will contain the elements of the chain stop computing the chain when you find a cached size a repeating item or the length is greater then the desired one if chain contains the exact amount of elements increase the counter function to perform the sum of the factorial of all the digits in number digit_factorial_sum 69 0 traceback most recent call last typeerror parameter number must be int digit_factorial_sum 1 traceback most recent call last valueerror parameter number must be greater than or equal to 0 digit_factorial_sum 0 1 digit_factorial_sum 69 363600 converts number in string to iterate on its digits and adds its factorial returns the number of numbers below number_limit that produce chains with exactly chain_length non repeating elements solution 10 0 1000 traceback most recent call last typeerror parameters chain_length and number_limit must be int solution 10 1000 0 traceback most recent call last typeerror parameters chain_length and number_limit must be int solution 0 1000 traceback most recent call last valueerror parameters chain_length and number_limit must be greater than 0 solution 10 0 traceback most recent call last valueerror parameters chain_length and number_limit must be greater than 0 solution 10 1000 26 the counter for the chains with the exact desired length the cached sizes of the previous chains the temporary set will contain the elements of the chain stop computing the chain when you find a cached size a repeating item or the length is greater then the desired one if chain contains the exact amount of elements increase the counter
from math import factorial DIGIT_FACTORIAL: dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def digit_factorial_sum(number: int) -> int: if not isinstance(number, int): raise TypeError("Parameter number must be int") if number < 0: raise ValueError("Parameter number must be greater than or equal to 0") return sum(DIGIT_FACTORIAL[digit] for digit in str(number)) def solution(chain_length: int = 60, number_limit: int = 1000000) -> int: if not isinstance(chain_length, int) or not isinstance(number_limit, int): raise TypeError("Parameters chain_length and number_limit must be int") if chain_length <= 0 or number_limit <= 0: raise ValueError( "Parameters chain_length and number_limit must be greater than 0" ) chains_counter = 0 chain_sets_lengths: dict[int, int] = {} for start_chain_element in range(1, number_limit): chain_set = set() chain_set_length = 0 chain_element = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(chain_element) chain_set_length += 1 chain_element = digit_factorial_sum(chain_element) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] chain_sets_lengths[start_chain_element] = chain_set_length if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution()}")
project euler problem 75 https projecteuler netproblem75 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 12 cm 3 4 5 24 cm 6 8 10 30 cm 5 12 13 36 cm 9 12 15 40 cm 8 15 17 48 cm 12 16 20 in contrast some lengths of wire like 20 cm cannot be bent to form an integer sided right angle triangle and other lengths allow more than one solution to be found for example using 120 cm it is possible to form exactly three different integer sided right angle triangles 120 cm 30 40 50 20 48 52 24 45 51 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 solution we generate all pythagorean triples using euclid s formula and keep track of the frequencies of the perimeters reference https en wikipedia orgwikipythagoreantriplegeneratingatriple return the number of values of l limit such that a wire of length l can be formmed into an integer sided right angle triangle in exactly one way solution50 6 solution1000 112 solution50000 5502 return the number of values of l limit such that a wire of length l can be formmed into an integer sided right angle triangle in exactly one way solution 50 6 solution 1000 112 solution 50000 5502
from collections import defaultdict from math import gcd def solution(limit: int = 1500000) -> int: frequencies: defaultdict = defaultdict(int) euclid_m = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2): if gcd(euclid_m, euclid_n) > 1: continue primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1) if __name__ == "__main__": print(f"{solution() = }")
counting summations problem 76 https projecteuler netproblem76 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 returns the number of different ways the number m can be written as a sum of at least two positive integers solution100 190569291 solution50 204225 solution30 5603 solution10 41 solution5 6 solution3 2 solution2 1 solution1 0 returns the number of different ways the number m can be written as a sum of at least two positive integers solution 100 190569291 solution 50 204225 solution 30 5603 solution 10 41 solution 5 6 solution 3 2 solution 2 1 solution 1 0
def solution(m: int = 100) -> int: memo = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n > k: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] - 1 if __name__ == "__main__": print(solution(int(input("Enter a number: ").strip())))
project euler problem 77 https projecteuler netproblem77 it is possible to write ten as the sum of primes in exactly five different ways 7 3 5 5 5 3 2 3 3 2 2 2 2 2 2 2 what is the first value which can be written as the sum of primes in over five thousand different ways return a set of integers corresponding to unique prime partitions of n the unique prime partitions can be represented as unique prime decompositions e g 73 73 12 3322 3322 36 partition10 32 36 21 25 30 partition15 192 160 105 44 112 243 180 150 216 26 125 126 lenpartition20 26 return the smallest integer that can be written as the sum of primes in over m unique ways solution4 10 solution500 45 solution1000 53 return a set of integers corresponding to unique prime partitions of n the unique prime partitions can be represented as unique prime decompositions e g 7 3 7 3 12 3 3 2 2 3 3 2 2 36 partition 10 32 36 21 25 30 partition 15 192 160 105 44 112 243 180 150 216 26 125 126 len partition 20 26 return the smallest integer that can be written as the sum of primes in over m unique ways solution 4 10 solution 500 45 solution 1000 53
from __future__ import annotations from functools import lru_cache from math import ceil NUM_PRIMES = 100 primes = set(range(3, NUM_PRIMES, 2)) primes.add(2) prime: int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100) def partition(number_to_partition: int) -> set[int]: if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} ret: set[int] = set() prime: int sub: int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime): ret.add(sub * prime) return ret def solution(number_unique_partitions: int = 5000) -> int | None: for number_to_partition in range(1, NUM_PRIMES): if len(partition(number_to_partition)) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"{solution() = }")
problem 78 url https projecteuler netproblem78 statement let pn 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 p57 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 pn is divisible by one million solution1 1 solution9 14 solution 55374 solution 1 1 solution 9 14 solution 55374
import itertools def solution(number: int = 1000000) -> int: partitions = [1] for i in itertools.count(len(partitions)): item = 0 for j in itertools.count(1): sign = -1 if j % 2 == 0 else +1 index = (j * j * 3 - j) // 2 if index > i: break item += partitions[i - index] * sign item %= number index += j if index > i: break item += partitions[i - index] * sign item %= number if item == 0: return i partitions.append(item) return 0 if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
project euler problem 79 https projecteuler netproblem79 passcode derivation a common security method used for online banking is to ask the user for three random characters from a passcode for example if the passcode was 531278 they may ask for the 2nd 3rd and 5th characters the expected reply would be 317 the text file keylog txt contains fifty successful login attempts 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 returns the shortest possible secret passcode of unknown length findsecretpasscode135 259 235 189 690 168 120 136 289 589 160 165 580 369 250 280 12365890 findsecretpasscode426 281 061 819 268 406 420 428 209 689 019 421 469 261 681 201 4206819 split each login by character e g 319 3 1 9 returns the shortest possible secret passcode of unknown length for successful login attempts given by inputfile text file solutionkeylogtest txt 6312980 returns the shortest possible secret passcode of unknown length find_secret_passcode 135 259 235 189 690 168 120 136 289 589 160 165 580 369 250 280 12365890 find_secret_passcode 426 281 061 819 268 406 420 428 209 689 019 421 469 261 681 201 4206819 split each login by character e g 319 3 1 9 returns the shortest possible secret passcode of unknown length for successful login attempts given by input_file text file solution keylog_test txt 6312980
import itertools from pathlib import Path def find_secret_passcode(logins: list[str]) -> int: split_logins = [tuple(login) for login in logins] unique_chars = {char for login in split_logins for char in login} for permutation in itertools.permutations(unique_chars): satisfied = True for login in logins: if not ( permutation.index(login[0]) < permutation.index(login[1]) < permutation.index(login[2]) ): satisfied = False break if satisfied: return int("".join(permutation)) raise Exception("Unable to find the secret passcode") def solution(input_file: str = "keylog.txt") -> int: logins = Path(__file__).parent.joinpath(input_file).read_text().splitlines() return find_secret_passcode(logins) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 80 https projecteuler netproblem80 sandeep gupta problem statement 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 time 5 october 2020 18 30 to evaluate the sum used decimal python module to calculate the decimal places up to 100 the most important thing would be take calculate a few extra places for decimal otherwise there will be rounding error solution 40886 to evaluate the sum used decimal python module to calculate the decimal places up to 100 the most important thing would be take calculate a few extra places for decimal otherwise there will be rounding error solution 40886
import decimal def solution() -> int: answer = 0 decimal_context = decimal.Context(prec=105) for i in range(2, 100): number = decimal.Decimal(i) sqrt_number = number.sqrt(decimal_context) if len(str(sqrt_number)) > 1: answer += int(str(sqrt_number)[0]) sqrt_number_str = str(sqrt_number)[2:101] answer += sum(int(x) for x in sqrt_number_str) return answer if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")