repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_022/__init__.py
project_euler/problem_022/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_062/sol1.py
project_euler/problem_062/sol1.py
""" Project Euler 62 https://projecteuler.net/problem=62 The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). 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. """ from collections import defaultdict def solution(max_base: int = 5) -> int: """ 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 """ 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: """ Computes the sorted sequence of digits of the cube of num. >>> get_digits(3) '27' >>> get_digits(99) '027999' >>> get_digits(123) '0166788' """ return "".join(sorted(str(num**3))) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_062/__init__.py
project_euler/problem_062/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_021/sol1.py
project_euler/problem_021/sol1.py
""" Amicable Numbers Problem 21 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a β‰  b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ 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: """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 """ 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())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_021/__init__.py
project_euler/problem_021/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_037/sol1.py
project_euler/problem_037/sol1.py
""" Truncatable primes Problem 37: https://projecteuler.net/problem=37 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. """ from __future__ import annotations import math def is_prime(number: int) -> bool: """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 """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 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]: """ 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] """ 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: """ 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 """ return not ( len(str(n)) > 3 and (not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3]))) ) def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ 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: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_037/__init__.py
project_euler/problem_037/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_014/sol2.py
project_euler/problem_014/sol2.py
""" Problem 14: https://projecteuler.net/problem=14 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 β†’ n/2 (n is even) n β†’ 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 β†’ 40 β†’ 20 β†’ 10 β†’ 5 β†’ 16 β†’ 8 β†’ 4 β†’ 2 β†’ 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ from __future__ import annotations COLLATZ_SEQUENCE_LENGTHS = {1: 1} def collatz_sequence_length(n: int) -> int: """Returns the Collatz sequence length for n.""" 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: """Returns the number under n that generates the longest Collatz sequence. >>> solution(1000000) 837799 >>> solution(200) 171 >>> solution(5000) 3711 >>> solution(15000) 13255 """ result = max((collatz_sequence_length(i), i) for i in range(1, n)) return result[1] if __name__ == "__main__": print(solution(int(input().strip())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_014/sol1.py
project_euler/problem_014/sol1.py
""" Problem 14: https://projecteuler.net/problem=14 Problem Statement: The following iterative sequence is defined for the set of positive integers: n β†’ n/2 (n is even) n β†’ 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 β†’ 40 β†’ 20 β†’ 10 β†’ 5 β†’ 16 β†’ 8 β†’ 4 β†’ 2 β†’ 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ def solution(n: int = 1000000) -> int: """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 """ 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())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_014/__init__.py
project_euler/problem_014/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_047/sol1.py
project_euler/problem_047/sol1.py
""" Combinatoric selections Problem 47 The first two consecutive numbers to have two distinct prime factors are: 14 = 2 x 7 15 = 3 x 5 The first three consecutive numbers to have three distinct prime factors are: 644 = 2Β² x 7 x 23 645 = 3 x 5 x 43 646 = 2 x 17 x 19. Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers? """ from functools import lru_cache def unique_prime_factors(n: int) -> set: """ Find unique prime factors of an integer. Tests include sorting because only the set 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] """ 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: """ Memoize upf() length results for a given value. >>> upf_len(14) 2 """ return len(unique_prime_factors(num)) def equality(iterable: list) -> bool: """ Check the equality of ALL elements in an iterable >>> equality([1, 2, 3, 4]) False >>> equality([2, 2, 2, 2]) True >>> equality([1, 2, 3, 2, 1]) False """ return len(set(iterable)) in (0, 1) def run(n: int) -> list[int]: """ Runs core process to find problem solution. >>> run(3) [644, 645, 646] """ # Incrementor variable for our group list comprehension. # This is the first number in each list of values # to test. base = 2 while True: # Increment each value of a generated range group = [base + i for i in range(n)] # Run elements through the unique_prime_factors function # Append our target number to the end. checker = [upf_len(x) for x in group] checker.append(n) # If all numbers in the list are equal, return the group variable. if equality(checker): return group # Increment our base variable by 1 base += 1 def solution(n: int = 4) -> int | None: """Return the first value of the first four consecutive integers to have four distinct prime factors each. >>> solution() 134043 """ results = run(n) return results[0] if len(results) else None if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_047/__init__.py
project_euler/problem_047/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_036/sol1.py
project_euler/problem_036/sol1.py
""" Project Euler Problem 36 https://projecteuler.net/problem=36 Problem Statement: Double-base 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.) """ from __future__ import annotations def is_palindrome(n: int | str) -> bool: """ 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 """ n = str(n) return n == n[::-1] def solution(n: int = 1000000): """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 """ 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()))))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_036/__init__.py
project_euler/problem_036/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_113/sol1.py
project_euler/problem_113/sol1.py
""" Project Euler Problem 113: https://projecteuler.net/problem=113 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349. As n increases, the proportion of bouncy numbers below n increases such that there are only 12951 numbers below one-million that are not bouncy and only 277032 non-bouncy numbers below 10^10. How many numbers below a googol (10^100) are not bouncy? """ def choose(n: int, r: int) -> int: """ Calculate the binomial coefficient c(n,r) using the multiplicative formula. >>> choose(4,2) 6 >>> choose(5,3) 10 >>> choose(20,6) 38760 """ ret = 1.0 for i in range(1, r + 1): ret *= (n + 1 - i) / i return round(ret) def non_bouncy_exact(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_exact(1) 9 >>> non_bouncy_exact(6) 7998 >>> non_bouncy_exact(10) 136126 """ return choose(8 + n, n) + choose(9 + n, n) - 10 def non_bouncy_upto(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_upto(1) 9 >>> non_bouncy_upto(6) 12951 >>> non_bouncy_upto(10) 277032 """ return sum(non_bouncy_exact(i) for i in range(1, n + 1)) def solution(num_digits: int = 100) -> int: """ Calculate the number of non-bouncy numbers less than a googol. >>> solution(6) 12951 >>> solution(10) 277032 """ return non_bouncy_upto(num_digits) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_113/__init__.py
project_euler/problem_113/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_131/sol1.py
project_euler/problem_131/sol1.py
""" Project Euler Problem 131: https://projecteuler.net/problem=131 There are some prime values, p, for which there exists a positive integer, n, such that the expression n^3 + n^2p is a perfect cube. For example, when p = 19, 8^3 + 8^2 x 19 = 12^3. What is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred. How many primes below one million have this remarkable property? """ from math import isqrt def is_prime(number: int) -> bool: """ Determines whether number is prime >>> is_prime(3) True >>> is_prime(4) False """ return all(number % divisor != 0 for divisor in range(2, isqrt(number) + 1)) def solution(max_prime: int = 10**6) -> int: """ Returns number of primes below max_prime with the property >>> solution(100) 4 """ primes_count = 0 cube_index = 1 prime_candidate = 7 while prime_candidate < max_prime: primes_count += is_prime(prime_candidate) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_131/__init__.py
project_euler/problem_131/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_055/sol1.py
project_euler/problem_055/sol1.py
""" Lychrel numbers Problem 55: https://projecteuler.net/problem=55 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 ten-thousand, 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, 28-digits). Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994. How many Lychrel numbers are there below ten-thousand? """ def is_palindrome(n: int) -> bool: """ Returns True if a number is palindrome. >>> is_palindrome(12567321) False >>> is_palindrome(1221) True >>> is_palindrome(9876789) True """ return str(n) == str(n)[::-1] def sum_reverse(n: int) -> int: """ Returns the sum of n and reverse of n. >>> sum_reverse(123) 444 >>> sum_reverse(3478) 12221 >>> sum_reverse(12) 33 """ return int(n) + int(str(n)[::-1]) def solution(limit: int = 10000) -> int: """ Returns the count of all lychrel numbers below limit. >>> solution(10000) 249 >>> solution(5000) 76 >>> solution(1000) 13 """ 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() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_055/__init__.py
project_euler/problem_055/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_024/sol1.py
project_euler/problem_024/sol1.py
""" 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? """ from itertools import permutations def solution(): """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. >>> solution() '2783915460' """ result = list(map("".join, permutations("0123456789"))) return result[999999] if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_024/__init__.py
project_euler/problem_024/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_020/sol2.py
project_euler/problem_020/sol2.py
""" Problem 20: https://projecteuler.net/problem=20 n! means n x (n - 1) x ... x 3 x 2 x 1 For example, 10! = 10 x 9 x ... x 3 x 2 x 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! """ from math import factorial def solution(num: int = 100) -> int: """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 """ return sum(int(x) for x in str(factorial(num))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_020/sol4.py
project_euler/problem_020/sol4.py
""" Problem 20: https://projecteuler.net/problem=20 n! means n x (n - 1) x ... x 3 x 2 x 1 For example, 10! = 10 x 9 x ... x 3 x 2 x 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! """ def solution(num: int = 100) -> int: """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 """ 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())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_020/sol3.py
project_euler/problem_020/sol3.py
""" Problem 20: https://projecteuler.net/problem=20 n! means n x (n - 1) x ... x 3 x 2 x 1 For example, 10! = 10 x 9 x ... x 3 x 2 x 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! """ from math import factorial def solution(num: int = 100) -> int: """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 """ return sum(map(int, str(factorial(num)))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_020/sol1.py
project_euler/problem_020/sol1.py
""" Problem 20: https://projecteuler.net/problem=20 n! means n x (n - 1) x ... x 3 x 2 x 1 For example, 10! = 10 x 9 x ... x 3 x 2 x 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! """ def factorial(num: int) -> int: """Find the factorial of a given number n""" fact = 1 for i in range(1, num + 1): fact *= i return fact def split_and_add(number: int) -> int: """Split number digits and add them.""" sum_of_digits = 0 while number > 0: last_digit = number % 10 sum_of_digits += last_digit number = number // 10 # Removing the last_digit from the given number return sum_of_digits def solution(num: int = 100) -> int: """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 """ nfact = factorial(num) result = split_and_add(nfact) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_020/__init__.py
project_euler/problem_020/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_234/sol1.py
project_euler/problem_234/sol1.py
""" https://projecteuler.net/problem=234 For an integer n β‰₯ 4, we define the lower prime square root of n, denoted by lps(n), as the largest prime ≀ √n and the upper prime square root of n, ups(n), as the smallest prime β‰₯ √n. So, for example, lps(4) = 2 = ups(4), lps(1000) = 31, ups(1000) = 37. Let us call an integer n β‰₯ 4 semidivisible, if one of lps(n) and ups(n) divides n, but not both. The sum of the semidivisible numbers not exceeding 15 is 30, the numbers are 8, 10 and 12. 15 is not semidivisible because it is a multiple of both lps(15) = 3 and ups(15) = 5. As a further example, the sum of the 92 semidivisible numbers up to 1000 is 34825. What is the sum of all semidivisible numbers not exceeding 999966663333 ? """ import math def prime_sieve(n: int) -> list: """ 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] """ 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 solution(limit: int = 999_966_663_333) -> int: """ Computes the solution to the problem up to the specified limit >>> solution(1000) 34825 >>> solution(10_000) 1134942 >>> solution(100_000) 36393008 """ primes_upper_bound = math.floor(math.sqrt(limit)) + 100 primes = prime_sieve(primes_upper_bound) matches_sum = 0 prime_index = 0 last_prime = primes[prime_index] while (last_prime**2) <= limit: next_prime = primes[prime_index + 1] lower_bound = last_prime**2 upper_bound = next_prime**2 # Get numbers divisible by lps(current) current = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) current = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps current = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair last_prime = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_234/__init__.py
project_euler/problem_234/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_188/sol1.py
project_euler/problem_188/sol1.py
""" Project Euler Problem 188: https://projecteuler.net/problem=188 The hyperexponentiation of a number The hyperexponentiation or tetration of a number a by a positive integer b, denoted by a↑↑b or b^a, is recursively defined by: a↑↑1 = a, a↑↑(k+1) = a(a↑↑k). Thus we have e.g. 3↑↑2 = 3^3 = 27, hence 3↑↑3 = 3^27 = 7625597484987 and 3↑↑4 is roughly 103.6383346400240996*10^12. Find the last 8 digits of 1777↑↑1855. References: - https://en.wikipedia.org/wiki/Tetration """ # small helper function for modular exponentiation (fast exponentiation algorithm) def _modexpt(base: int, exponent: int, modulo_value: int) -> int: """ Returns the modular exponentiation, that is the value of `base ** exponent % modulo_value`, without calculating the actual number. >>> _modexpt(2, 4, 10) 6 >>> _modexpt(2, 1024, 100) 16 >>> _modexpt(13, 65535, 7) 6 """ if exponent == 1: return base if exponent % 2 == 0: x = _modexpt(base, exponent // 2, modulo_value) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(base, exponent - 1, modulo_value)) % modulo_value def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int: """ Returns the last 8 digits of the hyperexponentiation of base by height, i.e. the number base↑↑height: >>> solution(base=3, height=2) 27 >>> solution(base=3, height=3) 97484987 >>> solution(base=123, height=456, digits=4) 2547 """ # calculate base↑↑height by right-assiciative repeated modular # exponentiation result = base for _ in range(1, height): result = _modexpt(base, result, 10**digits) return result if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_188/__init__.py
project_euler/problem_188/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_057/sol1.py
project_euler/problem_057/sol1.py
""" Project Euler Problem 57: https://projecteuler.net/problem=57 It is possible to show that the square root of two can be expressed as an infinite continued fraction. sqrt(2) = 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 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator? """ def solution(n: int = 1000) -> int: """ 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 """ 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() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_057/__init__.py
project_euler/problem_057/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_016/sol2.py
project_euler/problem_016/sol2.py
""" Problem 16: https://projecteuler.net/problem=16 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power: int = 1000) -> int: """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ 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())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_016/sol1.py
project_euler/problem_016/sol1.py
""" Problem 16: https://projecteuler.net/problem=16 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power: int = 1000) -> int: """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ 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)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_016/__init__.py
project_euler/problem_016/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_068/sol1.py
project_euler/problem_068/sol1.py
""" Project Euler Problem 68: https://projecteuler.net/problem=68 Magic 5-gon ring Problem Statement: Consider the following "magic" 3-gon 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 9-digit strings; the maximum string for a 3-gon ring is 432621513. Using the numbers 1 to 10, and depending on arrangements, it is possible to form 16- and 17-digit strings. What is the maximum 16-digit string for a "magic" 5-gon ring? """ from itertools import permutations def solution(gon_side: int = 5) -> int: """ 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] """ if gon_side < 3 or gon_side > 5: raise 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 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]: """ 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] """ 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: """ 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 """ 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_068/__init__.py
project_euler/problem_068/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_587/sol1.py
project_euler/problem_587/sol1.py
""" Project Euler Problem 587: https://projecteuler.net/problem=587 A square is drawn around a circle as shown in the diagram below on the left. We shall call the blue shaded region the L-section. A line is drawn from the bottom left of the square to the top right as shown in the diagram on the right. We shall call the orange shaded region a concave triangle. It should be clear that the concave triangle occupies exactly half of the L-section. Two circles are placed next to each other horizontally, a rectangle is drawn around both circles, and a line is drawn from the bottom left to the top right as shown in the diagram below. This time the concave triangle occupies approximately 36.46% of the L-section. If n circles are placed next to each other horizontally, a rectangle is drawn around the n circles, and a line is drawn from the bottom left to the top right, then it can be shown that the least value of n for which the concave triangle occupies less than 10% of the L-section is n = 15. What is the least value of n for which the concave triangle occupies less than 0.1% of the L-section? """ from itertools import count from math import asin, pi, sqrt def circle_bottom_arc_integral(point: float) -> float: """ Returns integral of circle bottom arc y = 1 / 2 - sqrt(1 / 4 - (x - 1 / 2) ^ 2) >>> circle_bottom_arc_integral(0) 0.39269908169872414 >>> circle_bottom_arc_integral(1 / 2) 0.44634954084936207 >>> circle_bottom_arc_integral(1) 0.5 """ return ( (1 - 2 * point) * sqrt(point - point**2) + 2 * point + asin(sqrt(1 - point)) ) / 4 def concave_triangle_area(circles_number: int) -> float: """ Returns area of concave triangle >>> concave_triangle_area(1) 0.026825229575318944 >>> concave_triangle_area(2) 0.01956236140083944 """ intersection_y = (circles_number + 1 - sqrt(2 * circles_number)) / ( 2 * (circles_number**2 + 1) ) intersection_x = circles_number * intersection_y triangle_area = intersection_x * intersection_y / 2 concave_region_area = circle_bottom_arc_integral( 1 / 2 ) - circle_bottom_arc_integral(intersection_x) return triangle_area + concave_region_area def solution(fraction: float = 1 / 1000) -> int: """ Returns least value of n for which the concave triangle occupies less than fraction of the L-section >>> solution(1 / 10) 15 """ l_section_area = (1 - pi / 4) / 4 for n in count(1): if concave_triangle_area(n) / l_section_area < fraction: return n return -1 if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_587/__init__.py
project_euler/problem_587/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_094/sol1.py
project_euler/problem_094/sol1.py
""" Project Euler Problem 94: https://projecteuler.net/problem=94 It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units. We shall define an almost equilateral triangle to be a triangle for which two sides are equal and the third differs by no more than one unit. Find the sum of the perimeters of all almost equilateral triangles with integral side lengths and area and whose perimeters do not exceed one billion (1,000,000,000). """ def solution(max_perimeter: int = 10**9) -> int: """ Returns the sum of the perimeters of all almost equilateral triangles with integral side lengths and area and whose perimeters do not exceed max_perimeter >>> solution(20) 16 """ prev_value = 1 value = 2 perimeters_sum = 0 i = 0 perimeter = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value perimeter = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_094/__init__.py
project_euler/problem_094/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_117/sol1.py
project_euler/problem_117/sol1.py
""" Project Euler Problem 117: https://projecteuler.net/problem=117 Using a combination of grey square tiles and oblong tiles chosen from: red tiles (measuring two units), green tiles (measuring three units), and blue tiles (measuring four units), it is possible to tile a row measuring five units in length in exactly fifteen different ways. |grey|grey|grey|grey|grey| |red,red|grey|grey|grey| |grey|red,red|grey|grey| |grey|grey|red,red|grey| |grey|grey|grey|red,red| |red,red|red,red|grey| |red,red|grey|red,red| |grey|red,red|red,red| |green,green,green|grey|grey| |grey|green,green,green|grey| |grey|grey|green,green,green| |red,red|green,green,green| |green,green,green|red,red| |blue,blue,blue,blue|grey| |grey|blue,blue,blue,blue| How many ways can a row measuring fifty units in length be tiled? NOTE: This is related to Problem 116 (https://projecteuler.net/problem=116). """ def solution(length: int = 50) -> int: """ Returns the number of ways can a row of the given length be tiled >>> solution(5) 15 """ ways_number = [1] * (length + 1) for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_117/__init__.py
project_euler/problem_117/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_164/sol1.py
project_euler/problem_164/sol1.py
""" Project Euler Problem 164: https://projecteuler.net/problem=164 Three Consecutive Digital Sum Limit How many 20 digit numbers n (without any leading zero) exist such that no three consecutive digits of n have a sum greater than 9? Brute-force recursive solution with caching of intermediate results. """ def solve( digit: int, prev1: int, prev2: int, sum_max: int, first: bool, cache: dict[str, int] ) -> int: """ Solve for remaining 'digit' digits, with previous 'prev1' digit, and previous-previous 'prev2' digit, total sum of 'sum_max'. Pass around 'cache' to store/reuse intermediate results. >>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=True, cache={}) 9 >>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=False, cache={}) 10 """ if digit == 0: return 1 cache_str = f"{digit},{prev1},{prev2}" if cache_str in cache: return cache[cache_str] comb = 0 for curr in range(sum_max - prev1 - prev2 + 1): if first and curr == 0: continue comb += solve( digit=digit - 1, prev1=curr, prev2=prev1, sum_max=sum_max, first=False, cache=cache, ) cache[cache_str] = comb return comb def solution(n_digits: int = 20) -> int: """ Solves the problem for n_digits number of digits. >>> solution(2) 45 >>> solution(10) 21838806 """ cache: dict[str, int] = {} return solve(digit=n_digits, prev1=0, prev2=0, sum_max=9, first=True, cache=cache) if __name__ == "__main__": print(f"{solution(10) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_164/__init__.py
project_euler/problem_164/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_058/sol1.py
project_euler/problem_058/sol1.py
""" Project Euler Problem 58:https://projecteuler.net/problem=58 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 8/13 β‰ˆ 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 j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1) j*j+4*(j+1). Out of these 4 only the first three can become prime because last one reduces to (j+2)*(j+2). So we check individually each one of these before incrementing our count of current primes. """ import math def is_prime(number: int) -> bool: """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 """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 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: """ 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 """ 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()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_058/__init__.py
project_euler/problem_058/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_012/sol2.py
project_euler/problem_012/sol2.py
""" 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? """ 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(): """Returns the value of the first triangle number to have over five hundred divisors. >>> solution() 76576500 """ return next(i for i in triangle_number_generator() if count_divisors(i) > 500) if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_012/sol1.py
project_euler/problem_012/sol1.py
""" 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? """ 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(): """Returns the value of the first triangle number to have over five hundred divisors. >>> solution() 76576500 """ 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_012/__init__.py
project_euler/problem_012/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_011/sol2.py
project_euler/problem_011/sol2.py
""" 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 """ import os def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: grid = [] for _ in range(20): grid.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] maximum = max(maximum, temp) # down for i in range(17): for j in range(20): temp = grid[i][j] * grid[i + 1][j] * grid[i + 2][j] * grid[i + 3][j] maximum = max(maximum, temp) # diagonal 1 for i in range(17): for j in range(17): temp = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) maximum = max(maximum, temp) # diagonal 2 for i in range(17): for j in range(3, 20): temp = ( grid[i][j] * grid[i + 1][j - 1] * grid[i + 2][j - 2] * grid[i + 3][j - 3] ) maximum = max(maximum, temp) return maximum if __name__ == "__main__": print(solution())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_011/sol1.py
project_euler/problem_011/sol1.py
""" 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 """ 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 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) 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] # Left-to-right diagonal (\) product 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] ) # Right-to-left diagonal(/) product 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 ) largest = max(largest, max_product) return largest def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_011/__init__.py
project_euler/problem_011/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_067/sol2.py
project_euler/problem_067/sol2.py
""" 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 Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution() -> int: """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_067/sol1.py
project_euler/problem_067/sol1.py
""" 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 Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution(): """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_067/__init__.py
project_euler/problem_067/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_030/sol1.py
project_euler/problem_030/sol1.py
"""Problem Statement (Digit Fifth Powers): https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 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. 9^5 = 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 """ DIGITS_FIFTH_POWER = {str(digit): digit**5 for digit in range(10)} def digits_fifth_powers_sum(number: int) -> int: """ >>> digits_fifth_powers_sum(1234) 1300 """ 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_030/__init__.py
project_euler/problem_030/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_203/sol1.py
project_euler/problem_203/sol1.py
""" Project Euler Problem 203: https://projecteuler.net/problem=203 The binomial coefficients (n k) can be arranged in triangular form, Pascal's triangle, like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 ......... It can be seen that the first eight rows of Pascal's triangle contain twelve distinct numbers: 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 21 and 35. A positive integer n is called squarefree if no square of a prime divides n. Of the twelve distinct numbers in the first eight rows of Pascal's triangle, all except 4 and 20 are squarefree. The sum of the distinct squarefree numbers in the first eight rows is 105. Find the sum of the distinct squarefree numbers in the first 51 rows of Pascal's triangle. References: - https://en.wikipedia.org/wiki/Pascal%27s_triangle """ from __future__ import annotations def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]: """ Returns the unique coefficients of a Pascal's triangle of depth "depth". The coefficients of this triangle are symmetric. A further improvement to this method could be to calculate the coefficients once per level. Nonetheless, the current implementation is fast enough for the original problem. >>> get_pascal_triangle_unique_coefficients(1) {1} >>> get_pascal_triangle_unique_coefficients(2) {1} >>> get_pascal_triangle_unique_coefficients(3) {1, 2} >>> get_pascal_triangle_unique_coefficients(8) {1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21} """ coefficients = {1} previous_coefficients = [1] for _ in range(2, depth + 1): coefficients_begins_one = [*previous_coefficients, 0] coefficients_ends_one = [0, *previous_coefficients] previous_coefficients = [] for x, y in zip(coefficients_begins_one, coefficients_ends_one): coefficients.add(x + y) previous_coefficients.append(x + y) return coefficients def get_squarefrees(unique_coefficients: set[int]) -> set[int]: """ Calculates the squarefree numbers inside unique_coefficients. Based on the definition of a non-squarefree number, then any non-squarefree n can be decomposed as n = p*p*r, where p is positive prime number and r is a positive integer. Under the previous formula, any coefficient that is lower than p*p is squarefree as r cannot be negative. On the contrary, if any r exists such that n = p*p*r, then the number is non-squarefree. >>> get_squarefrees({1}) {1} >>> get_squarefrees({1, 2}) {1, 2} >>> get_squarefrees({1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21}) {1, 2, 3, 5, 6, 7, 35, 10, 15, 21} """ non_squarefrees = set() for number in unique_coefficients: divisor = 2 copy_number = number while divisor**2 <= copy_number: multiplicity = 0 while copy_number % divisor == 0: copy_number //= divisor multiplicity += 1 if multiplicity >= 2: non_squarefrees.add(number) break divisor += 1 return unique_coefficients.difference(non_squarefrees) def solution(n: int = 51) -> int: """ Returns the sum of squarefrees for a given Pascal's Triangle of depth n. >>> solution(1) 1 >>> solution(8) 105 >>> solution(9) 175 """ unique_coefficients = get_pascal_triangle_unique_coefficients(n) squarefrees = get_squarefrees(unique_coefficients) return sum(squarefrees) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_203/__init__.py
project_euler/problem_203/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_102/sol1.py
project_euler/problem_102/sol1.py
""" Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≀ x, y ≀ 1000, such that a triangle is formed. Consider the following two triangles: A(-340,495), B(-153,-910), C(835,-947) X(-175,41), Y(-421,-714), Z(574,-645) It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not. Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the coordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin. NOTE: The first two examples in the file represent the triangles in the example given above. """ from __future__ import annotations from pathlib import Path def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: """ Return the 2-d vector product of two vectors. >>> vector_product((1, 2), (-5, 0)) 10 >>> vector_product((3, 1), (6, 10)) 24 """ return point1[0] * point2[1] - point1[1] * point2[0] def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: """ Check if the triangle given by the points A(x1, y1), B(x2, y2), C(x3, y3) contains the origin. >>> contains_origin(-340, 495, -153, -910, 835, -947) True >>> contains_origin(-175, 41, -421, -714, 574, -645) False """ point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) a: float = -vector_product(point_a, point_a_to_b) / vector_product( point_a_to_c, point_a_to_b ) b: float = +vector_product(point_a, point_a_to_c) / vector_product( point_a_to_c, point_a_to_b ) return a > 0 and b > 0 and a + b < 1 def solution(filename: str = "p102_triangles.txt") -> int: """ Find the number of triangles whose interior contains the origin. >>> solution("test_triangles.txt") 1 """ data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] for line in data.strip().split("\n"): triangles.append([int(number) for number in line.split(",")]) ret: int = 0 triangle: list[int] for triangle in triangles: ret += contains_origin(*triangle) return ret if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_102/__init__.py
project_euler/problem_102/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_100/sol1.py
project_euler/problem_100/sol1.py
""" Project Euler Problem 100: https://projecteuler.net/problem=100 If a box contains twenty-one coloured discs, composed of fifteen blue discs and six red discs, and two discs were taken at random, it can be seen that the probability of taking two blue discs, P(BB) = (15/21) x (14/20) = 1/2. The next such arrangement, for which there is exactly 50% chance of taking two blue discs at random, is a box containing eighty-five blue discs and thirty-five red discs. By finding the first arrangement to contain over 10^12 = 1,000,000,000,000 discs in total, determine the number of blue discs that the box would contain. """ def solution(min_total: int = 10**12) -> int: """ Returns the number of blue discs for the first arrangement to contain over min_total discs in total >>> solution(2) 3 >>> solution(4) 15 >>> solution(21) 85 """ prev_numerator = 1 prev_denominator = 0 numerator = 1 denominator = 1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_100/__init__.py
project_euler/problem_100/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_092/sol1.py
project_euler/problem_092/sol1.py
""" Project Euler Problem 092: https://projecteuler.net/problem=92 Square digit chains A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 β†’ 32 β†’ 13 β†’ 10 β†’ 1 β†’ 1 85 β†’ 89 β†’ 145 β†’ 42 β†’ 20 β†’ 4 β†’ 16 β†’ 37 β†’ 58 β†’ 89 Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. How many starting numbers below ten million will arrive at 89? """ DIGITS_SQUARED = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(100000)] def next_number(number: int) -> int: """ Returns the next number of the chain by adding the square of each digit to form a new number. For example, if number = 12, next_number() will return 1^2 + 2^2 = 5. Therefore, 5 is the next number of the chain. >>> next_number(44) 32 >>> next_number(10) 1 >>> next_number(32) 13 """ sum_of_digits_squared = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution CHAINS: list[bool | None] = [None] * 10000000 CHAINS[0] = True CHAINS[57] = False def chain(number: int) -> bool: """ The function generates the chain of numbers until the next number is 1 or 89. For example, if starting number is 44, then the function generates the following chain of numbers: 44 β†’ 32 β†’ 13 β†’ 10 β†’ 1 β†’ 1. Once the next number generated is 1 or 89, the function returns whether or not the next number generated by next_number() is 1. >>> chain(10) True >>> chain(58) False >>> chain(1) True """ if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore[return-value] number_chain = chain(next_number(number)) CHAINS[number - 1] = number_chain while number < 10000000: CHAINS[number - 1] = number_chain number *= 10 return number_chain def solution(number: int = 10000000) -> int: """ The function returns the number of integers that end up being 89 in each chain. The function accepts a range number and the function checks all the values under value number. >>> solution(100) 80 >>> solution(10000000) 8581146 """ for i in range(1, number): if CHAINS[i] is None: chain(i + 1) return CHAINS[:number].count(False) if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_092/__init__.py
project_euler/problem_092/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_039/sol1.py
project_euler/problem_039/sol1.py
""" Problem 39: https://projecteuler.net/problem=39 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? """ from __future__ import annotations import typing from collections import Counter def pythagorean_triple(max_perimeter: int) -> typing.Counter[int]: """ 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}) """ 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: """ Returns perimeter with maximum solutions. >>> solution(100) 90 >>> solution(200) 180 >>> solution(1000) 840 """ triplets = pythagorean_triple(n) return triplets.most_common(1)[0][0] if __name__ == "__main__": print(f"Perimeter {solution()} has maximum solutions")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_039/__init__.py
project_euler/problem_039/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_112/sol1.py
project_euler/problem_112/sol1.py
""" Problem 112: https://projecteuler.net/problem=112 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number, for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ def check_bouncy(n: int) -> bool: """ Returns True if number is bouncy, False otherwise >>> check_bouncy(6789) False >>> check_bouncy(-12345) False >>> check_bouncy(0) False >>> check_bouncy(6.74) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(132475) True >>> check_bouncy(34) False >>> check_bouncy(341) True >>> check_bouncy(47) False >>> check_bouncy(-12.54) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(-6548) True """ if not isinstance(n, int): raise ValueError("check_bouncy() accepts only integer arguments") str_n = str(n) sorted_str_n = "".join(sorted(str_n)) return str_n not in {sorted_str_n, sorted_str_n[::-1]} def solution(percent: float = 99) -> int: """ Returns the least number for which the proportion of bouncy numbers is exactly 'percent' >>> solution(50) 538 >>> solution(90) 21780 >>> solution(80) 4770 >>> solution(105) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 >>> solution(100.011) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 """ if not 0 < percent < 100: raise ValueError("solution() only accepts values from 0 to 100") bouncy_num = 0 num = 1 while True: if check_bouncy(num): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f"{solution(99)}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_112/__init__.py
project_euler/problem_112/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_015/sol1.py
project_euler/problem_015/sol1.py
""" Problem 15: https://projecteuler.net/problem=15 Starting in the top left corner of a 2x2 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 20x20 grid? """ from math import factorial def solution(n: int = 20) -> int: """ 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 """ n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... 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.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_015/__init__.py
project_euler/problem_015/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_004/sol2.py
project_euler/problem_004/sol2.py
""" Project Euler Problem 4: https://projecteuler.net/problem=4 Largest palindrome product A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers. References: - https://en.wikipedia.org/wiki/Palindromic_number """ def solution(n: int = 998001) -> int: """ Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 """ answer = 0 for i in range(999, 99, -1): # 3 digit numbers range from 999 down to 100 for j in range(999, 99, -1): product_string = str(i * j) if product_string == product_string[::-1] and i * j < n: answer = max(answer, i * j) return answer if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_004/sol1.py
project_euler/problem_004/sol1.py
""" Project Euler Problem 4: https://projecteuler.net/problem=4 Largest palindrome product A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers. References: - https://en.wikipedia.org/wiki/Palindromic_number """ def solution(n: int = 998001) -> int: """ Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 >>> solution(10000) Traceback (most recent call last): ... ValueError: That number is larger than our acceptable range. """ # fetches the next number for number in range(n - 1, 9999, -1): str_number = str(number) # checks whether 'str_number' is a palindrome. if str_number == str_number[::-1]: divisor = 999 # if 'number' is a product of two 3-digit numbers # then number is the answer otherwise fetch next number. while divisor != 99: if (number % divisor == 0) and (len(str(number // divisor)) == 3.0): return number divisor -= 1 raise ValueError("That number is larger than our acceptable range.") if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_004/__init__.py
project_euler/problem_004/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_026/sol1.py
project_euler/problem_026/sol1.py
""" Euler Problem 26 https://projecteuler.net/problem=26 Problem Statement: A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. """ def solution(numerator: int = 1, digit: int = 1000) -> int: """ 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 """ 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 # Tests if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_026/__init__.py
project_euler/problem_026/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_035/sol1.py
project_euler/problem_035/sol1.py
""" Project Euler Problem 35 https://projecteuler.net/problem=35 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. """ 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: """ For 2 <= n <= 1000000, return True if n is prime. >>> is_prime(87) False >>> is_prime(23) True >>> is_prime(25363) False """ return sieve[n] def contains_an_even_digit(n: int) -> bool: """ 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 any(digit in "02468" for digit in str(n)) def find_circular_primes(limit: int = 1000000) -> list[int]: """ Return circular primes below limit. >>> len(find_circular_primes(100)) 13 >>> len(find_circular_primes(1000000)) 55 """ result = [2] # result already includes the number 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: """ >>> solution() 55 """ return len(find_circular_primes()) if __name__ == "__main__": print(f"{len(find_circular_primes()) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_035/__init__.py
project_euler/problem_035/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_073/sol1.py
project_euler/problem_073/sol1.py
""" Project Euler Problem 73: https://projecteuler.net/problem=73 Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≀ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that there are 3 fractions between 1/3 and 1/2. How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≀ 12,000? """ from math import gcd def solution(max_d: int = 12_000) -> int: """ 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 """ fractions_number = 0 for d in range(max_d + 1): n_start = d // 3 + 1 n_step = 1 if d % 2 == 0: n_start += 1 - n_start % 2 n_step = 2 for n in range(n_start, (d + 1) // 2, n_step): if gcd(n, d) == 1: fractions_number += 1 return fractions_number if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_073/__init__.py
project_euler/problem_073/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_104/sol1.py
project_euler/problem_104/sol1.py
""" Project Euler Problem 104 : https://projecteuler.net/problem=104 The Fibonacci sequence is defined by the recurrence relation: Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1. It turns out that F541, which contains 113 digits, is the first Fibonacci number for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, but not necessarily in order). And F2749, which contains 575 digits, is the first Fibonacci number for which the first nine digits are 1-9 pandigital. Given that Fk is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k. """ import sys sys.set_int_max_str_digits(0) def check(number: int) -> bool: """ Takes a number and checks if it is pandigital both from start and end >>> check(123456789987654321) True >>> check(120000987654321) False >>> check(1234567895765677987654321) True """ check_last = [0] * 11 check_front = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False if not f: return f # mark first 9 numbers number = int(str(number)[:9]) for _ in range(9): check_front[int(number % 10)] = 1 number = number // 10 # check first 9 numbers for pandigitality for x in range(9): if not check_front[x + 1]: f = False return f def check1(number: int) -> bool: """ Takes a number and checks if it is pandigital from END >>> check1(123456789987654321) True >>> check1(120000987654321) True >>> check1(12345678957656779870004321) False """ check_last = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False return f def solution() -> int: """ Outputs the answer is the least Fibonacci number pandigital from both sides. >>> solution() 329468 """ a = 1 b = 1 c = 2 # temporary Fibonacci numbers a1 = 1 b1 = 1 c1 = 2 # temporary Fibonacci numbers mod 1e9 # mod m=1e9, done for fast optimisation tocheck = [0] * 1000000 m = 1000000000 for x in range(1000000): c1 = (a1 + b1) % m a1 = b1 % m b1 = c1 % m if check1(b1): tocheck[x + 3] = 1 for x in range(1000000): c = a + b a = b b = c # perform check only if in tocheck if tocheck[x + 3] and check(b): return x + 3 # first 2 already done return -1 if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_104/__init__.py
project_euler/problem_104/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_042/solution42.py
project_euler/problem_042/solution42.py
""" The nth term of the sequence of triangle numbers is given by, tn = Β½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? """ import os # Precomputes a list of the 100 first triangular numbers TRIANGULAR_NUMBERS = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def solution(): """ Finds the amount of triangular words in the words file. >>> solution() 162 """ 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_042/__init__.py
project_euler/problem_042/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_043/sol1.py
project_euler/problem_043/sol1.py
""" Problem 43: https://projecteuler.net/problem=43 The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ from itertools import permutations def is_substring_divisible(num: tuple) -> bool: """ 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 """ 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: """ Returns the sum of all pandigital numbers which pass the divisibility tests. >>> solution(10) 16695334890 """ return sum( int("".join(map(str, num))) for num in permutations(range(n)) if is_substring_divisible(num) ) if __name__ == "__main__": print(f"{solution() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_043/__init__.py
project_euler/problem_043/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_053/sol1.py
project_euler/problem_053/sol1.py
""" 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!(n-r)!),where r ≀ n, n! = nx(n-1)x...x3x2x1, and 0! = 1. It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066. How many, not necessarily distinct, values of nCr, for 1 ≀ n ≀ 100, are greater than one-million? """ from math import factorial def combinations(n, r): return factorial(n) / (factorial(r) * factorial(n - r)) def solution(): """Returns the number of values of nCr, for 1 ≀ n ≀ 100, are greater than one-million >>> solution() 4075 """ 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_053/__init__.py
project_euler/problem_053/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_051/sol1.py
project_euler/problem_051/sol1.py
""" https://projecteuler.net/problem=51 Prime digit replacements Problem 51 By replacing the 1st digit of the 2-digit 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 56**3 with the same digit, this 5-digit 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. """ from __future__ import annotations from collections import Counter def prime_sieve(n: int) -> list[int]: """ 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] """ 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]]: """ 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]] """ 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: """ Returns the solution of the problem >>> solution(2) 229399 >>> solution(3) 221311 """ numbers_checked = set() # Filter primes with less than 3 replaceable digits 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())
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_051/__init__.py
project_euler/problem_051/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_077/sol1.py
project_euler/problem_077/sol1.py
""" Project Euler Problem 77: https://projecteuler.net/problem=77 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? """ 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]: """ 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 """ 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: """ 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 """ 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() = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_077/__init__.py
project_euler/problem_077/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_028/sol1.py
project_euler/problem_028/sol1.py
""" Problem 28 Url: https://projecteuler.net/problem=28 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? """ from math import ceil def solution(n: int = 1001) -> int: """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 """ total = 1 for i in range(1, 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")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_028/__init__.py
project_euler/problem_028/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_076/sol1.py
project_euler/problem_076/sol1.py
""" Counting Summations Problem 76: https://projecteuler.net/problem=76 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? """ def solution(m: int = 100) -> int: """ 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 """ 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())))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_076/__init__.py
project_euler/problem_076/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_071/sol1.py
project_euler/problem_071/sol1.py
""" Ordered fractions Problem 71 https://projecteuler.net/problem=71 Consider the fraction n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≀ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. 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 3/7. """ def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ 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 """ 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))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_071/__init__.py
project_euler/problem_071/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false