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_121/__init__.py | project_euler/problem_121/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_099/sol1.py | project_euler/problem_099/sol1.py | """
Problem:
Comparing two numbers written in index form like 2'11 and 3'7 is not difficult, as any
calculator would confirm that 2^11 = 2048 < 3^7 = 2187.
However, confirming that 632382^518061 > 519432^525806 would be much more difficult, as
both numbers contain over three million digits.
Using base_exp.txt, a 22K text file containing one thousand lines with a base/exponent
pair on each line, determine which line number has the greatest numerical value.
NOTE: The first two lines in the file represent the numbers in the example given above.
"""
import os
from math import log10
def solution(data_file: str = "base_exp.txt") -> int:
"""
>>> solution()
709
"""
largest: float = 0
result = 0
for i, line in enumerate(open(os.path.join(os.path.dirname(__file__), data_file))):
a, x = list(map(int, line.split(",")))
if x * log10(a) > largest:
largest = x * log10(a)
result = i + 1
return result
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_099/__init__.py | project_euler/problem_099/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_101/sol1.py | project_euler/problem_101/sol1.py | """
If we are presented with the first k terms of a sequence it is impossible to say with
certainty the value of the next term, as there are infinitely many polynomial functions
that can model the sequence.
As an example, let us consider the sequence of cube
numbers. This is defined by the generating function,
u(n) = n3: 1, 8, 27, 64, 125, 216, ...
Suppose we were only given the first two terms of this sequence. Working on the
principle that "simple is best" we should assume a linear relationship and predict the
next term to be 15 (common difference 7). Even if we were presented with the first three
terms, by the same principle of simplicity, a quadratic relationship should be
assumed.
We shall define OP(k, n) to be the nth term of the optimum polynomial
generating function for the first k terms of a sequence. It should be clear that
OP(k, n) will accurately generate the terms of the sequence for n β€ k, and potentially
the first incorrect term (FIT) will be OP(k, k+1); in which case we shall call it a
bad OP (BOP).
As a basis, if we were only given the first term of sequence, it would be most
sensible to assume constancy; that is, for n β₯ 2, OP(1, n) = u(1).
Hence we obtain the
following OPs for the cubic sequence:
OP(1, n) = 1 1, 1, 1, 1, ...
OP(2, n) = 7n-6 1, 8, 15, ...
OP(3, n) = 6n^2-11n+6 1, 8, 27, 58, ...
OP(4, n) = n^3 1, 8, 27, 64, 125, ...
Clearly no BOPs exist for k β₯ 4.
By considering the sum of FITs generated by the BOPs (indicated in red above), we
obtain 1 + 15 + 58 = 74.
Consider the following tenth degree polynomial generating function:
1 - n + n^2 - n^3 + n^4 - n^5 + n^6 - n^7 + n^8 - n^9 + n^10
Find the sum of FITs for the BOPs.
"""
from __future__ import annotations
from collections.abc import Callable
Matrix = list[list[float | int]]
def solve(matrix: Matrix, vector: Matrix) -> Matrix:
"""
Solve the linear system of equations Ax = b (A = "matrix", b = "vector")
for x using Gaussian elimination and back substitution. We assume that A
is an invertible square matrix and that b is a column vector of the
same height.
>>> solve([[1, 0], [0, 1]], [[1],[2]])
[[1.0], [2.0]]
>>> solve([[2, 1, -1],[-3, -1, 2],[-2, 1, 2]],[[8], [-11],[-3]])
[[2.0], [3.0], [-1.0]]
"""
size: int = len(matrix)
augmented: Matrix = [[0 for _ in range(size + 1)] for _ in range(size)]
row: int
row2: int
col: int
col2: int
pivot_row: int
ratio: float
for row in range(size):
for col in range(size):
augmented[row][col] = matrix[row][col]
augmented[row][size] = vector[row][0]
row = 0
col = 0
while row < size and col < size:
# pivoting
pivot_row = max((abs(augmented[row2][col]), row2) for row2 in range(col, size))[
1
]
if augmented[pivot_row][col] == 0:
col += 1
continue
else:
augmented[row], augmented[pivot_row] = augmented[pivot_row], augmented[row]
for row2 in range(row + 1, size):
ratio = augmented[row2][col] / augmented[row][col]
augmented[row2][col] = 0
for col2 in range(col + 1, size + 1):
augmented[row2][col2] -= augmented[row][col2] * ratio
row += 1
col += 1
# back substitution
for col in range(1, size):
for row in range(col):
ratio = augmented[row][col] / augmented[col][col]
for col2 in range(col, size + 1):
augmented[row][col2] -= augmented[col][col2] * ratio
# round to get rid of numbers like 2.000000000000004
return [
[round(augmented[row][size] / augmented[row][row], 10)] for row in range(size)
]
def interpolate(y_list: list[int]) -> Callable[[int], int]:
"""
Given a list of data points (1,y0),(2,y1), ..., return a function that
interpolates the data points. We find the coefficients of the interpolating
polynomial by solving a system of linear equations corresponding to
x = 1, 2, 3...
>>> interpolate([1])(3)
1
>>> interpolate([1, 8])(3)
15
>>> interpolate([1, 8, 27])(4)
58
>>> interpolate([1, 8, 27, 64])(6)
216
"""
size: int = len(y_list)
matrix: Matrix = [[0 for _ in range(size)] for _ in range(size)]
vector: Matrix = [[0] for _ in range(size)]
coeffs: Matrix
x_val: int
y_val: int
col: int
for x_val, y_val in enumerate(y_list):
for col in range(size):
matrix[x_val][col] = (x_val + 1) ** (size - col - 1)
vector[x_val][0] = y_val
coeffs = solve(matrix, vector)
def interpolated_func(var: int) -> int:
"""
>>> interpolate([1])(3)
1
>>> interpolate([1, 8])(3)
15
>>> interpolate([1, 8, 27])(4)
58
>>> interpolate([1, 8, 27, 64])(6)
216
"""
return sum(
round(coeffs[x_val][0]) * (var ** (size - x_val - 1))
for x_val in range(size)
)
return interpolated_func
def question_function(variable: int) -> int:
"""
The generating function u as specified in the question.
>>> question_function(0)
1
>>> question_function(1)
1
>>> question_function(5)
8138021
>>> question_function(10)
9090909091
"""
return (
1
- variable
+ variable**2
- variable**3
+ variable**4
- variable**5
+ variable**6
- variable**7
+ variable**8
- variable**9
+ variable**10
)
def solution(func: Callable[[int], int] = question_function, order: int = 10) -> int:
"""
Find the sum of the FITs of the BOPS. For each interpolating polynomial of order
1, 2, ... , 10, find the first x such that the value of the polynomial at x does
not equal u(x).
>>> solution(lambda n: n ** 3, 3)
74
"""
data_points: list[int] = [func(x_val) for x_val in range(1, order + 1)]
polynomials: list[Callable[[int], int]] = [
interpolate(data_points[:max_coeff]) for max_coeff in range(1, order + 1)
]
ret: int = 0
poly: Callable[[int], int]
x_val: int
for poly in polynomials:
x_val = 1
while func(x_val) == poly(x_val):
x_val += 1
ret += poly(x_val)
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_101/__init__.py | project_euler/problem_101/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_097/sol1.py | project_euler/problem_097/sol1.py | """
The first known prime found to exceed one million digits was discovered in 1999,
and is a Mersenne prime of the form 2**6972593 - 1; it contains exactly 2,098,960
digits. Subsequently other Mersenne primes, of the form 2**p - 1, have been found
which contain more digits.
However, in 2004 there was found a massive non-Mersenne prime which contains
2,357,207 digits: (28433 * (2 ** 7830457 + 1)).
Find the last ten digits of this prime number.
"""
def solution(n: int = 10) -> str:
"""
Returns the last n digits of NUMBER.
>>> solution()
'8739992577'
>>> solution(8)
'39992577'
>>> solution(1)
'7'
>>> solution(-1)
Traceback (most recent call last):
...
ValueError: Invalid input
>>> solution(8.3)
Traceback (most recent call last):
...
ValueError: Invalid input
>>> solution("a")
Traceback (most recent call last):
...
ValueError: Invalid input
"""
if not isinstance(n, int) or n < 0:
raise ValueError("Invalid input")
modulus = 10**n
number = 28433 * (pow(2, 7830457, modulus)) + 1
return str(number % modulus)
if __name__ == "__main__":
from doctest import testmod
testmod()
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_097/__init__.py | project_euler/problem_097/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_135/sol1.py | project_euler/problem_135/sol1.py | """
Project Euler Problem 135: https://projecteuler.net/problem=135
Given the positive integers, x, y, and z, are consecutive terms of an arithmetic
progression, the least value of the positive integer, n, for which the equation,
x2 - y2 - z2 = n, has exactly two solutions is n = 27:
342 - 272 - 202 = 122 - 92 - 62 = 27
It turns out that n = 1155 is the least value which has exactly ten solutions.
How many values of n less than one million have exactly ten distinct solutions?
Taking x, y, z of the form a + d, a, a - d respectively, the given equation reduces to
a * (4d - a) = n.
Calculating no of solutions for every n till 1 million by fixing a, and n must be a
multiple of a. Total no of steps = n * (1/1 + 1/2 + 1/3 + 1/4 + ... + 1/n), so roughly
O(nlogn) time complexity.
"""
def solution(limit: int = 1000000) -> int:
"""
returns the values of n less than or equal to the limit
have exactly ten distinct solutions.
>>> solution(100)
0
>>> solution(10000)
45
>>> solution(50050)
292
"""
limit = limit + 1
frequency = [0] * limit
for first_term in range(1, limit):
for n in range(first_term, limit, first_term):
common_difference = first_term + n / first_term
if common_difference % 4: # d must be divisible by 4
continue
else:
common_difference /= 4
if (
first_term > common_difference
and first_term < 4 * common_difference
): # since x, y, z are positive integers
frequency[n] += 1 # so z > 0, a > d and 4d < a
count = sum(1 for x in frequency[1:limit] if x == 10)
return 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_135/__init__.py | project_euler/problem_135/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_032/sol32.py | project_euler/problem_032/sol32.py | """
We shall say that an n-digit number is pandigital if it makes use of all the
digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through
5 pandigital.
The product 7254 is unusual, as the identity, 39 x 186 = 7254, containing
multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can
be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only
include it once in your sum.
"""
import itertools
def is_combination_valid(combination):
"""
Checks if a combination (a tuple of 9 digits)
is a valid product equation.
>>> is_combination_valid(('3', '9', '1', '8', '6', '7', '2', '5', '4'))
True
>>> is_combination_valid(('1', '2', '3', '4', '5', '6', '7', '8', '9'))
False
"""
return (
int("".join(combination[0:2])) * int("".join(combination[2:5]))
== int("".join(combination[5:9]))
) or (
int("".join(combination[0])) * int("".join(combination[1:5]))
== int("".join(combination[5:9]))
)
def solution():
"""
Finds the sum of all products whose multiplicand/multiplier/product identity
can be written as a 1 through 9 pandigital
>>> solution()
45228
"""
return sum(
{
int("".join(pandigital[5:9]))
for pandigital in itertools.permutations("123456789")
if is_combination_valid(pandigital)
}
)
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_032/__init__.py | project_euler/problem_032/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_109/sol1.py | project_euler/problem_109/sol1.py | """
In the game of darts a player throws three darts at a target board which is
split into twenty equal sized sections numbered one to twenty.
οΏΌ
The score of a dart is determined by the number of the region that the dart
lands in. A dart landing outside the red/green outer ring scores zero. The black
and cream regions inside this ring represent single scores. However, the red/green
outer ring and middle ring score double and treble scores respectively.
At the centre of the board are two concentric circles called the bull region, or
bulls-eye. The outer bull is worth 25 points and the inner bull is a double,
worth 50 points.
There are many variations of rules but in the most popular game the players will
begin with a score 301 or 501 and the first player to reduce their running total
to zero is a winner. However, it is normal to play a "doubles out" system, which
means that the player must land a double (including the double bulls-eye at the
centre of the board) on their final dart to win; any other dart that would reduce
their running total to one or lower means the score for that set of three darts
is "bust".
When a player is able to finish on their current score it is called a "checkout"
and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull).
There are exactly eleven distinct ways to checkout on a score of 6:
D3
D1 D2
S2 D2
D2 D1
S4 D1
S1 S1 D2
S1 T1 D1
S1 S3 D1
D1 D1 D1
D1 S2 D1
S2 S2 D1
Note that D1 D2 is considered different to D2 D1 as they finish on different
doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1.
In addition we shall not include misses in considering combinations; for example,
D3 is the same as 0 D3 and 0 0 D3.
Incredibly there are 42336 distinct ways of checking out in total.
How many distinct ways can a player checkout with a score less than 100?
Solution:
We first construct a list of the possible dart values, separated by type.
We then iterate through the doubles, followed by the possible 2 following throws.
If the total of these three darts is less than the given limit, we increment
the counter.
"""
from itertools import combinations_with_replacement
def solution(limit: int = 100) -> int:
"""
Count the number of distinct ways a player can checkout with a score
less than limit.
>>> solution(171)
42336
>>> solution(50)
12577
"""
singles: list[int] = [*list(range(1, 21)), 25]
doubles: list[int] = [2 * x for x in range(1, 21)] + [50]
triples: list[int] = [3 * x for x in range(1, 21)]
all_values: list[int] = singles + doubles + triples + [0]
num_checkouts: int = 0
double: int
throw1: int
throw2: int
checkout_total: int
for double in doubles:
for throw1, throw2 in combinations_with_replacement(all_values, 2):
checkout_total = double + throw1 + throw2
if checkout_total < limit:
num_checkouts += 1
return num_checkouts
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_109/__init__.py | project_euler/problem_109/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_078/sol1.py | project_euler/problem_078/sol1.py | """
Problem 78
Url: https://projecteuler.net/problem=78
Statement:
Let p(n) represent the number of different ways in which n coins
can be separated into piles. For example, five coins can be separated
into piles in exactly seven different ways, so p(5)=7.
OOOOO
OOOO O
OOO OO
OOO O O
OO OO O
OO O O O
O O O O O
Find the least value of n for which p(n) is divisible by one million.
"""
import itertools
def solution(number: int = 1000000) -> int:
"""
>>> solution(1)
1
>>> solution(9)
14
>>> solution()
55374
"""
partitions = [1]
for i in itertools.count(len(partitions)):
item = 0
for j in itertools.count(1):
sign = -1 if j % 2 == 0 else +1
index = (j * j * 3 - j) // 2
if index > i:
break
item += partitions[i - index] * sign
item %= number
index += j
if index > i:
break
item += partitions[i - index] * sign
item %= number
if item == 0:
return i
partitions.append(item)
return 0
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_078/__init__.py | project_euler/problem_078/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_007/sol2.py | project_euler/problem_007/sol2.py | """
Project Euler Problem 7: https://projecteuler.net/problem=7
10001st prime
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
can see that the 6th prime is 13.
What is the 10001st prime number?
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
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.
Returns boolean representing primality of given number (i.e., if the
result is true, then the number is indeed prime else it is not).
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
>>> is_prime(0)
False
>>> is_prime(1)
False
"""
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(nth: int = 10001) -> int:
"""
Returns the n-th prime number.
>>> solution(6)
13
>>> solution(1)
2
>>> solution(3)
5
>>> solution(20)
71
>>> solution(50)
229
>>> solution(100)
541
>>> solution(3.4)
5
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter nth must be greater than or equal to one.
>>> solution(-17)
Traceback (most recent call last):
...
ValueError: Parameter nth must be greater than or equal to one.
>>> solution([])
Traceback (most recent call last):
...
TypeError: Parameter nth must be int or castable to int.
>>> solution("asd")
Traceback (most recent call last):
...
TypeError: Parameter nth must be int or castable to int.
"""
try:
nth = int(nth)
except (TypeError, ValueError):
raise TypeError("Parameter nth must be int or castable to int.") from None
if nth <= 0:
raise ValueError("Parameter nth must be greater than or equal to one.")
primes: list[int] = []
num = 2
while len(primes) < nth:
if is_prime(num):
primes.append(num)
num += 1
else:
num += 1
return primes[len(primes) - 1]
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_007/sol3.py | project_euler/problem_007/sol3.py | """
Project Euler Problem 7: https://projecteuler.net/problem=7
10001st prime
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
can see that the 6th prime is 13.
What is the 10001st prime number?
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
import itertools
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.
Returns boolean representing primality of given number (i.e., if the
result is true, then the number is indeed prime else it is not).
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
>>> is_prime(0)
False
>>> is_prime(1)
False
"""
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 prime_generator():
"""
Generate a sequence of prime numbers
"""
num = 2
while True:
if is_prime(num):
yield num
num += 1
def solution(nth: int = 10001) -> int:
"""
Returns the n-th prime number.
>>> solution(6)
13
>>> solution(1)
2
>>> solution(3)
5
>>> solution(20)
71
>>> solution(50)
229
>>> solution(100)
541
"""
return next(itertools.islice(prime_generator(), nth - 1, nth))
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_007/sol1.py | project_euler/problem_007/sol1.py | """
Project Euler Problem 7: https://projecteuler.net/problem=7
10001st prime
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we
can see that the 6th prime is 13.
What is the 10001st prime number?
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
from math import sqrt
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.
Returns boolean representing primality of given number (i.e., if the
result is true, then the number is indeed prime else it is not).
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
>>> is_prime(0)
False
>>> is_prime(1)
False
"""
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(sqrt(number) + 1), 6):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def solution(nth: int = 10001) -> int:
"""
Returns the n-th prime number.
>>> solution(6)
13
>>> solution(1)
2
>>> solution(3)
5
>>> solution(20)
71
>>> solution(50)
229
>>> solution(100)
541
"""
count = 0
number = 1
while count != nth and number < 3:
number += 1
if is_prime(number):
count += 1
while count != nth:
number += 2
if is_prime(number):
count += 1
return number
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_007/__init__.py | project_euler/problem_007/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_187/sol1.py | project_euler/problem_187/sol1.py | """
Project Euler Problem 187: https://projecteuler.net/problem=187
A composite is a number containing at least two prime factors.
For example, 15 = 3 x 5; 9 = 3 x 3; 12 = 2 x 2 x 3.
There are ten composites below thirty containing precisely two,
not necessarily distinct, prime factors: 4, 6, 9, 10, 14, 15, 21, 22, 25, 26.
How many composite integers, n < 10^8, have precisely two,
not necessarily distinct, prime factors?
"""
from math import isqrt
def slow_calculate_prime_numbers(max_number: int) -> list[int]:
"""
Returns prime numbers below max_number.
See: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
>>> slow_calculate_prime_numbers(10)
[2, 3, 5, 7]
>>> slow_calculate_prime_numbers(2)
[]
"""
# List containing a bool value for every number below max_number/2
is_prime = [True] * max_number
for i in range(2, isqrt(max_number - 1) + 1):
if is_prime[i]:
# Mark all multiple of i as not prime
for j in range(i**2, max_number, i):
is_prime[j] = False
return [i for i in range(2, max_number) if is_prime[i]]
def calculate_prime_numbers(max_number: int) -> list[int]:
"""
Returns prime numbers below max_number.
See: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
>>> calculate_prime_numbers(10)
[2, 3, 5, 7]
>>> calculate_prime_numbers(2)
[]
"""
if max_number <= 2:
return []
# List containing a bool value for every odd number below max_number/2
is_prime = [True] * (max_number // 2)
for i in range(3, isqrt(max_number - 1) + 1, 2):
if is_prime[i // 2]:
# Mark all multiple of i as not prime using list slicing
is_prime[i**2 // 2 :: i] = [False] * (
# Same as: (max_number - (i**2)) // (2 * i) + 1
# but faster than len(is_prime[i**2 // 2 :: i])
len(range(i**2 // 2, max_number // 2, i))
)
return [2] + [2 * i + 1 for i in range(1, max_number // 2) if is_prime[i]]
def slow_solution(max_number: int = 10**8) -> int:
"""
Returns the number of composite integers below max_number have precisely two,
not necessarily distinct, prime factors.
>>> slow_solution(30)
10
"""
prime_numbers = slow_calculate_prime_numbers(max_number // 2)
semiprimes_count = 0
left = 0
right = len(prime_numbers) - 1
while left <= right:
while prime_numbers[left] * prime_numbers[right] >= max_number:
right -= 1
semiprimes_count += right - left + 1
left += 1
return semiprimes_count
def while_solution(max_number: int = 10**8) -> int:
"""
Returns the number of composite integers below max_number have precisely two,
not necessarily distinct, prime factors.
>>> while_solution(30)
10
"""
prime_numbers = calculate_prime_numbers(max_number // 2)
semiprimes_count = 0
left = 0
right = len(prime_numbers) - 1
while left <= right:
while prime_numbers[left] * prime_numbers[right] >= max_number:
right -= 1
semiprimes_count += right - left + 1
left += 1
return semiprimes_count
def solution(max_number: int = 10**8) -> int:
"""
Returns the number of composite integers below max_number have precisely two,
not necessarily distinct, prime factors.
>>> solution(30)
10
"""
prime_numbers = calculate_prime_numbers(max_number // 2)
semiprimes_count = 0
right = len(prime_numbers) - 1
for left in range(len(prime_numbers)):
if left > right:
break
for r in range(right, left - 2, -1):
if prime_numbers[left] * prime_numbers[r] < max_number:
break
right = r
semiprimes_count += right - left + 1
return semiprimes_count
def benchmark() -> None:
"""
Benchmarks
"""
# Running performance benchmarks...
# slow_solution : 108.50874730000032
# while_sol : 28.09581200000048
# solution : 25.063097400000515
from timeit import timeit
print("Running performance benchmarks...")
print(f"slow_solution : {timeit('slow_solution()', globals=globals(), number=10)}")
print(f"while_sol : {timeit('while_solution()', globals=globals(), number=10)}")
print(f"solution : {timeit('solution()', globals=globals(), number=10)}")
if __name__ == "__main__":
print(f"Solution: {solution()}")
benchmark()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_187/__init__.py | project_euler/problem_187/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_041/sol1.py | project_euler/problem_041/sol1.py | """
Pandigital prime
Problem 41: https://projecteuler.net/problem=41
We shall say that an n-digit number is pandigital if it makes use of all the digits
1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3.
So we will check only 7 digit pandigital numbers to obtain the largest possible
pandigital prime.
"""
from __future__ import annotations
import math
from itertools import permutations
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(n: int = 7) -> int:
"""
Returns the maximum pandigital prime number of length n.
If there are none, then it will return 0.
>>> solution(2)
0
>>> solution(4)
4231
>>> solution(7)
7652413
"""
pandigital_str = "".join(str(i) for i in range(1, n + 1))
perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
pandigitals = [num for num in perm_list if is_prime(num)]
return max(pandigitals) if pandigitals else 0
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_041/__init__.py | project_euler/problem_041/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_045/sol1.py | project_euler/problem_045/sol1.py | """
Problem 45: https://projecteuler.net/problem=45
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ...
Pentagonal P(n) = (n * (3 * n - 1)) / 2 1, 5, 12, 22, 35, ...
Hexagonal H(n) = n * (2 * n - 1) 1, 6, 15, 28, 45, ...
It can be verified that T(285) = P(165) = H(143) = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
All triangle numbers are hexagonal numbers.
T(2n-1) = n * (2 * n - 1) = H(n)
So we shall check only for hexagonal numbers which are also pentagonal.
"""
def hexagonal_num(n: int) -> int:
"""
Returns nth hexagonal number
>>> hexagonal_num(143)
40755
>>> hexagonal_num(21)
861
>>> hexagonal_num(10)
190
"""
return n * (2 * n - 1)
def is_pentagonal(n: int) -> bool:
"""
Returns True if n is pentagonal, False otherwise.
>>> is_pentagonal(330)
True
>>> is_pentagonal(7683)
False
>>> is_pentagonal(2380)
True
"""
root = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def solution(start: int = 144) -> int:
"""
Returns the next number which is triangular, pentagonal and hexagonal.
>>> solution(144)
1533776805
"""
n = start
num = hexagonal_num(n)
while not is_pentagonal(num):
n += 1
num = hexagonal_num(n)
return num
if __name__ == "__main__":
print(f"{solution()} = ")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_045/__init__.py | project_euler/problem_045/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_120/sol1.py | project_euler/problem_120/sol1.py | """
Problem 120 Square remainders: https://projecteuler.net/problem=120
Description:
Let r be the remainder when (a-1)^n + (a+1)^n is divided by a^2.
For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 β‘ 42 mod 49.
And as n varies, so too will r, but for a = 7 it turns out that r_max = 42.
For 3 β€ a β€ 1000, find β r_max.
Solution:
On expanding the terms, we get 2 if n is even and 2an if n is odd.
For maximizing the value, 2an < a*a => n <= (a - 1)/2 (integer division)
"""
def solution(n: int = 1000) -> int:
"""
Returns β r_max for 3 <= a <= n as explained above
>>> solution(10)
300
>>> solution(100)
330750
>>> solution(1000)
333082500
"""
return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 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_120/__init__.py | project_euler/problem_120/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_082/sol1.py | project_euler/problem_082/sol1.py | """
Project Euler Problem 82: https://projecteuler.net/problem=82
The minimal path sum in the 5 by 5 matrix below, by starting in any cell
in the left column and finishing in any cell in the right column,
and only moving up, down, and right, is indicated in red and bold;
the sum is equal to 994.
131 673 [234] [103] [18]
[201] [96] [342] 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331
Find the minimal path sum from the left column to the right column in matrix.txt
(https://projecteuler.net/project/resources/p082_matrix.txt)
(right click and "Save Link/Target As..."),
a 31K text file containing an 80 by 80 matrix.
"""
import os
def solution(filename: str = "input.txt") -> int:
"""
Returns the minimal path sum in the matrix from the file, by starting in any cell
in the left column and finishing in any cell in the right column,
and only moving up, down, and right
>>> solution("test_matrix.txt")
994
"""
with open(os.path.join(os.path.dirname(__file__), filename)) as input_file:
matrix = [
[int(element) for element in line.split(",")]
for line in input_file.readlines()
]
rows = len(matrix)
cols = len(matrix[0])
minimal_path_sums = [[-1 for _ in range(cols)] for _ in range(rows)]
for i in range(rows):
minimal_path_sums[i][0] = matrix[i][0]
for j in range(1, cols):
for i in range(rows):
minimal_path_sums[i][j] = minimal_path_sums[i][j - 1] + matrix[i][j]
for i in range(1, rows):
minimal_path_sums[i][j] = min(
minimal_path_sums[i][j], minimal_path_sums[i - 1][j] + matrix[i][j]
)
for i in range(rows - 2, -1, -1):
minimal_path_sums[i][j] = min(
minimal_path_sums[i][j], minimal_path_sums[i + 1][j] + matrix[i][j]
)
return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums)
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_082/__init__.py | project_euler/problem_082/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_119/sol1.py | project_euler/problem_119/sol1.py | """
Problem 119: https://projecteuler.net/problem=119
Name: Digit power sum
The number 512 is interesting because it is equal to the sum of its digits
raised to some power: 5 + 1 + 2 = 8, and 8^3 = 512. Another example of a number
with this property is 614656 = 28^4. We shall define an to be the nth term of
this sequence and insist that a number must contain at least two digits to have a sum.
You are given that a2 = 512 and a10 = 614656. Find a30
"""
import math
def digit_sum(n: int) -> int:
"""
Returns the sum of the digits of the number.
>>> digit_sum(123)
6
>>> digit_sum(456)
15
>>> digit_sum(78910)
25
"""
return sum(int(digit) for digit in str(n))
def solution(n: int = 30) -> int:
"""
Returns the value of 30th digit power sum.
>>> solution(2)
512
>>> solution(5)
5832
>>> solution(10)
614656
"""
digit_to_powers = []
for digit in range(2, 100):
for power in range(2, 100):
number = int(math.pow(digit, power))
if digit == digit_sum(number):
digit_to_powers.append(number)
digit_to_powers.sort()
return digit_to_powers[n - 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_119/__init__.py | project_euler/problem_119/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_023/sol1.py | project_euler/problem_023/sol1.py | """
A perfect number is a number for which the sum of its proper divisors is exactly
equal to the number. For example, the sum of the proper divisors of 28 would be
1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n
and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
number that can be written as the sum of two abundant numbers is 24. By
mathematical analysis, it can be shown that all integers greater than 28123
can be written as the sum of two abundant numbers. However, this upper limit
cannot be reduced any further by analysis even though it is known that the
greatest number that cannot be expressed as the sum of two abundant numbers
is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum
of two abundant numbers.
"""
def solution(limit=28123):
"""
Finds the sum of all the positive integers which cannot be written as
the sum of two abundant numbers
as described by the statement above.
>>> solution()
4179871
"""
sum_divs = [1] * (limit + 1)
for i in range(2, int(limit**0.5) + 1):
sum_divs[i * i] += i
for k in range(i + 1, limit // i + 1):
sum_divs[k * i] += k + i
abundants = set()
res = 0
for n in range(1, limit + 1):
if sum_divs[n] > n:
abundants.add(n)
if not any((n - a in abundants) for a in abundants):
res += n
return res
if __name__ == "__main__":
print(solution())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_023/__init__.py | project_euler/problem_023/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_107/sol1.py | project_euler/problem_107/sol1.py | """
The following undirected network consists of seven vertices and twelve edges
with a total weight of 243.
οΏΌ
The same network can be represented by the matrix below.
A B C D E F G
A - 16 12 21 - - -
B 16 - - 17 20 - -
C 12 - - 28 - 31 -
D 21 17 28 - 18 19 23
E - 20 - 18 - - 11
F - - 31 19 - - 27
G - - - 23 11 27 -
However, it is possible to optimise the network by removing some edges and still
ensure that all points on the network remain connected. The network which achieves
the maximum saving is shown below. It has a weight of 93, representing a saving of
243 - 93 = 150 from the original network.
Using network.txt (right click and 'Save Link/Target As...'), a 6K text file
containing a network with forty vertices, and given in matrix form, find the maximum
saving which can be achieved by removing redundant edges whilst ensuring that the
network remains connected.
Solution:
We use Prim's algorithm to find a Minimum Spanning Tree.
Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm
"""
from __future__ import annotations
import os
from collections.abc import Mapping
EdgeT = tuple[int, int]
class Graph:
"""
A class representing an undirected weighted graph.
"""
def __init__(self, vertices: set[int], edges: Mapping[EdgeT, int]) -> None:
self.vertices: set[int] = vertices
self.edges: dict[EdgeT, int] = {
(min(edge), max(edge)): weight for edge, weight in edges.items()
}
def add_edge(self, edge: EdgeT, weight: int) -> None:
"""
Add a new edge to the graph.
>>> graph = Graph({1, 2}, {(2, 1): 4})
>>> graph.add_edge((3, 1), 5)
>>> sorted(graph.vertices)
[1, 2, 3]
>>> sorted([(v,k) for k,v in graph.edges.items()])
[(4, (1, 2)), (5, (1, 3))]
"""
self.vertices.add(edge[0])
self.vertices.add(edge[1])
self.edges[(min(edge), max(edge))] = weight
def prims_algorithm(self) -> Graph:
"""
Run Prim's algorithm to find the minimum spanning tree.
Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm
>>> graph = Graph({1,2,3,4},{(1,2):5, (1,3):10, (1,4):20, (2,4):30, (3,4):1})
>>> mst = graph.prims_algorithm()
>>> sorted(mst.vertices)
[1, 2, 3, 4]
>>> sorted(mst.edges)
[(1, 2), (1, 3), (3, 4)]
"""
subgraph: Graph = Graph({min(self.vertices)}, {})
min_edge: EdgeT
min_weight: int
edge: EdgeT
weight: int
while len(subgraph.vertices) < len(self.vertices):
min_weight = max(self.edges.values()) + 1
for edge, weight in self.edges.items():
if (edge[0] in subgraph.vertices) ^ (
edge[1] in subgraph.vertices
) and weight < min_weight:
min_edge = edge
min_weight = weight
subgraph.add_edge(min_edge, min_weight)
return subgraph
def solution(filename: str = "p107_network.txt") -> int:
"""
Find the maximum saving which can be achieved by removing redundant edges
whilst ensuring that the network remains connected.
>>> solution("test_network.txt")
150
"""
script_dir: str = os.path.abspath(os.path.dirname(__file__))
network_file: str = os.path.join(script_dir, filename)
edges: dict[EdgeT, int] = {}
data: list[str]
edge1: int
edge2: int
with open(network_file) as f:
data = f.read().strip().split("\n")
adjaceny_matrix = [line.split(",") for line in data]
for edge1 in range(1, len(adjaceny_matrix)):
for edge2 in range(edge1):
if adjaceny_matrix[edge1][edge2] != "-":
edges[(edge2, edge1)] = int(adjaceny_matrix[edge1][edge2])
graph: Graph = Graph(set(range(len(adjaceny_matrix))), edges)
subgraph: Graph = graph.prims_algorithm()
initial_total: int = sum(graph.edges.values())
optimal_total: int = sum(subgraph.edges.values())
return initial_total - optimal_total
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_107/__init__.py | project_euler/problem_107/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_069/sol1.py | project_euler/problem_069/sol1.py | """
Totient maximum
Problem 69: https://projecteuler.net/problem=69
Euler's Totient function, Ο(n) [sometimes called the phi function],
is used to determine the number of numbers less than n which are relatively prime to n.
For example, as 1, 2, 4, 5, 7, and 8,
are all less than nine and relatively prime to nine, Ο(9)=6.
n Relatively Prime Ο(n) n/Ο(n)
2 1 1 2
3 1,2 2 1.5
4 1,3 2 2
5 1,2,3,4 4 1.25
6 1,5 2 3
7 1,2,3,4,5,6 6 1.1666...
8 1,3,5,7 4 2
9 1,2,4,5,7,8 6 1.5
10 1,3,7,9 4 2.5
It can be seen that n=6 produces a maximum n/Ο(n) for n β€ 10.
Find the value of n β€ 1,000,000 for which n/Ο(n) is a maximum.
"""
def solution(n: int = 10**6) -> int:
"""
Returns solution to problem.
Algorithm:
1. Precompute Ο(k) for all natural k, k <= n using product formula (wikilink below)
https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler's_product_formula
2. Find k/Ο(k) for all k β€ n and return the k that attains maximum
>>> solution(10)
6
>>> solution(100)
30
>>> solution(9973)
2310
"""
if n <= 0:
raise ValueError("Please enter an integer greater than 0")
phi = list(range(n + 1))
for number in range(2, n + 1):
if phi[number] == number:
phi[number] -= 1
for multiple in range(number * 2, n + 1, number):
phi[multiple] = (phi[multiple] // number) * (number - 1)
answer = 1
for number in range(1, n + 1):
if (answer / phi[answer]) < (number / phi[number]):
answer = number
return answer
if __name__ == "__main__":
print(solution())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_069/__init__.py | project_euler/problem_069/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_080/sol1.py | project_euler/problem_080/sol1.py | """
Project Euler Problem 80: https://projecteuler.net/problem=80
Author: Sandeep Gupta
Problem statement: For the first one hundred natural numbers, find the total of
the digital sums of the first one hundred decimal digits for all the irrational
square roots.
Time: 5 October 2020, 18:30
"""
import decimal
def solution() -> int:
"""
To evaluate the sum, Used decimal python module to calculate the decimal
places up to 100, the most important thing would be take calculate
a few extra places for decimal otherwise there will be rounding
error.
>>> solution()
40886
"""
answer = 0
decimal_context = decimal.Context(prec=105)
for i in range(2, 100):
number = decimal.Decimal(i)
sqrt_number = number.sqrt(decimal_context)
if len(str(sqrt_number)) > 1:
answer += int(str(sqrt_number)[0])
sqrt_number_str = str(sqrt_number)[2:101]
answer += sum(int(x) for x in sqrt_number_str)
return answer
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_080/__init__.py | project_euler/problem_080/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_006/sol2.py | project_euler/problem_006/sol2.py | """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_cubes = (n * (n + 1) // 2) ** 2
sum_squares = n * (n + 1) * (2 * n + 1) // 6
return sum_cubes - sum_squares
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_006/sol4.py | project_euler/problem_006/sol4.py | """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_of_squares = n * (n + 1) * (2 * n + 1) / 6
square_of_sum = (n * (n + 1) / 2) ** 2
return int(square_of_sum - sum_of_squares)
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_006/sol3.py | project_euler/problem_006/sol3.py | """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
import math
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_of_squares = sum(i * i for i in range(1, n + 1))
square_of_sum = int(math.pow(sum(range(1, n + 1)), 2))
return square_of_sum - sum_of_squares
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_006/sol1.py | project_euler/problem_006/sol1.py | """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_of_squares = 0
sum_of_ints = 0
for i in range(1, n + 1):
sum_of_squares += i**2
sum_of_ints += i
return sum_of_ints**2 - sum_of_squares
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_006/__init__.py | project_euler/problem_006/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_089/sol1.py | project_euler/problem_089/sol1.py | """
Project Euler Problem 89: https://projecteuler.net/problem=89
For a number written in Roman numerals to be considered valid there are basic rules
which must be followed. Even though the rules allow some numbers to be expressed in
more than one way there is always a "best" way of writing a particular number.
For example, it would appear that there are at least six ways of writing the number
sixteen:
IIIIIIIIIIIIIIII
VIIIIIIIIIII
VVIIIIII
XIIIIII
VVVI
XVI
However, according to the rules only XIIIIII and XVI are valid, and the last example
is considered to be the most efficient, as it uses the least number of numerals.
The 11K text file, roman.txt (right click and 'Save Link/Target As...'), contains one
thousand numbers written in valid, but not necessarily minimal, Roman numerals; see
About... Roman Numerals for the definitive rules for this problem.
Find the number of characters saved by writing each of these in their minimal form.
Note: You can assume that all the Roman numerals in the file contain no more than four
consecutive identical units.
"""
import os
SYMBOLS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
def parse_roman_numerals(numerals: str) -> int:
"""
Converts a string of roman numerals to an integer.
e.g.
>>> parse_roman_numerals("LXXXIX")
89
>>> parse_roman_numerals("IIII")
4
"""
total_value = 0
index = 0
while index < len(numerals) - 1:
current_value = SYMBOLS[numerals[index]]
next_value = SYMBOLS[numerals[index + 1]]
if current_value < next_value:
total_value -= current_value
else:
total_value += current_value
index += 1
total_value += SYMBOLS[numerals[index]]
return total_value
def generate_roman_numerals(num: int) -> str:
"""
Generates a string of roman numerals for a given integer.
e.g.
>>> generate_roman_numerals(89)
'LXXXIX'
>>> generate_roman_numerals(4)
'IV'
"""
numerals = ""
m_count = num // 1000
numerals += m_count * "M"
num %= 1000
c_count = num // 100
if c_count == 9:
numerals += "CM"
c_count -= 9
elif c_count == 4:
numerals += "CD"
c_count -= 4
if c_count >= 5:
numerals += "D"
c_count -= 5
numerals += c_count * "C"
num %= 100
x_count = num // 10
if x_count == 9:
numerals += "XC"
x_count -= 9
elif x_count == 4:
numerals += "XL"
x_count -= 4
if x_count >= 5:
numerals += "L"
x_count -= 5
numerals += x_count * "X"
num %= 10
if num == 9:
numerals += "IX"
num -= 9
elif num == 4:
numerals += "IV"
num -= 4
if num >= 5:
numerals += "V"
num -= 5
numerals += num * "I"
return numerals
def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int:
"""
Calculates and returns the answer to project euler problem 89.
>>> solution("/numeralcleanup_test.txt")
16
"""
savings = 0
with open(os.path.dirname(__file__) + roman_numerals_filename) as file1:
lines = file1.readlines()
for line in lines:
original = line.strip()
num = parse_roman_numerals(original)
shortened = generate_roman_numerals(num)
savings += len(original) - len(shortened)
return savings
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_089/__init__.py | project_euler/problem_089/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_018/__init__.py | project_euler/problem_018/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_018/solution.py | project_euler/problem_018/solution.py | """
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
"""
import os
def solution():
"""
Finds the maximum total in a triangle as described by the problem statement
above.
>>> solution()
1074
"""
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
with open(triangle) as f:
triangle = f.readlines()
a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle]
for i in range(1, len(a)):
for j in range(len(a[i])):
number1 = a[i - 1][j] if j != len(a[i - 1]) else 0
number2 = a[i - 1][j - 1] if j > 0 else 0
a[i][j] += max(number1, number2)
return max(a[-1])
if __name__ == "__main__":
print(solution())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_072/sol2.py | project_euler/problem_072/sol2.py | """
Project Euler Problem 72: https://projecteuler.net/problem=72
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 21 elements in this set.
How many elements would be contained in the set of reduced proper fractions
for d β€ 1,000,000?
"""
def solution(limit: int = 1000000) -> int:
"""
Return the number of reduced proper fractions with denominator less than limit.
>>> solution(8)
21
>>> solution(1000)
304191
"""
primes = set(range(3, limit, 2))
primes.add(2)
for p in range(3, limit, 2):
if p not in primes:
continue
primes.difference_update(set(range(p * p, limit, p)))
phi = [float(n) for n in range(limit + 1)]
for p in primes:
for n in range(p, limit + 1, p):
phi[n] *= 1 - 1 / p
return int(sum(phi[2:]))
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_072/sol1.py | project_euler/problem_072/sol1.py | """
Problem 72 Counting fractions: https://projecteuler.net/problem=72
Description:
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 21 elements in this set.
How many elements would be contained in the set of reduced proper fractions for
d β€ 1,000,000?
Solution:
Number of numbers between 1 and n that are coprime to n is given by the Euler's Totient
function, phi(n). So, the answer is simply the sum of phi(n) for 2 <= n <= 1,000,000
Sum of phi(d), for all d|n = n. This result can be used to find phi(n) using a sieve.
Time: 1 sec
"""
import numpy as np
def solution(limit: int = 1_000_000) -> int:
"""
Returns an integer, the solution to the problem
>>> solution(10)
31
>>> solution(100)
3043
>>> solution(1_000)
304191
"""
# generating an array from -1 to limit
phi = np.arange(-1, limit)
for i in range(2, limit + 1):
if phi[i] == i - 1:
ind = np.arange(2 * i, limit + 1, i) # indexes for selection
phi[ind] -= phi[ind] // i
return int(np.sum(phi[2 : limit + 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_072/__init__.py | project_euler/problem_072/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_029/sol1.py | project_euler/problem_029/sol1.py | """
Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab
for 2 <= a <= 100 and 2 <= b <= 100?
"""
def solution(n: int = 100) -> int:
"""Returns the number of distinct terms in the sequence generated by a^b
for 2 <= a <= 100 and 2 <= b <= 100.
>>> solution(100)
9183
>>> solution(50)
2184
>>> solution(20)
324
>>> solution(5)
15
>>> solution(2)
1
>>> solution(1)
0
"""
collect_powers = set()
current_pow = 0
n = n + 1 # maximum limit
for a in range(2, n):
for b in range(2, n):
current_pow = a**b # calculates the current power
collect_powers.add(current_pow) # adds the result to the set
return len(collect_powers)
if __name__ == "__main__":
print("Number of terms ", 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_029/__init__.py | project_euler/problem_029/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_081/sol1.py | project_euler/problem_081/sol1.py | """
Problem 81: https://projecteuler.net/problem=81
In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right,
by only moving to the right and down, is indicated in bold red and is equal to 2427.
[131] 673 234 103 18
[201] [96] [342] 965 150
630 803 [746] [422] 111
537 699 497 [121] 956
805 732 524 [37] [331]
Find the minimal path sum from the top left to the bottom right by only moving right
and down in matrix.txt (https://projecteuler.net/project/resources/p081_matrix.txt),
a 31K text file containing an 80 by 80 matrix.
"""
import os
def solution(filename: str = "matrix.txt") -> int:
"""
Returns the minimal path sum from the top left to the bottom right of the matrix.
>>> solution()
427337
"""
with open(os.path.join(os.path.dirname(__file__), filename)) as in_file:
data = in_file.read()
grid = [[int(cell) for cell in row.split(",")] for row in data.strip().splitlines()]
dp = [[0 for cell in row] for row in grid]
n = len(grid[0])
dp = [[0 for i in range(n)] for j in range(n)]
dp[0][0] = grid[0][0]
for i in range(1, n):
dp[0][i] = grid[0][i] + dp[0][i - 1]
for i in range(1, n):
dp[i][0] = grid[i][0] + dp[i - 1][0]
for i in range(1, n):
for j in range(1, n):
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])
return dp[-1][-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_081/__init__.py | project_euler/problem_081/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_010/sol2.py | project_euler/problem_010/sol2.py | """
Project Euler Problem 10: https://projecteuler.net/problem=10
Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
import math
from collections.abc import Iterator
from itertools import takewhile
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.
Returns boolean representing primality of given number num (i.e., if the
result is true, then the number is indeed prime else it is not).
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
>>> is_prime(0)
False
>>> is_prime(1)
False
"""
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 prime_generator() -> Iterator[int]:
"""
Generate a list sequence of prime numbers
"""
num = 2
while True:
if is_prime(num):
yield num
num += 1
def solution(n: int = 2000000) -> int:
"""
Returns the sum of all the primes below n.
>>> solution(1000)
76127
>>> solution(5000)
1548136
>>> solution(10000)
5736396
>>> solution(7)
10
"""
return sum(takewhile(lambda x: x < n, prime_generator()))
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_010/sol3.py | project_euler/problem_010/sol3.py | """
Project Euler Problem 10: https://projecteuler.net/problem=10
Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
References:
- https://en.wikipedia.org/wiki/Prime_number
- https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def solution(n: int = 2000000) -> int:
"""
Returns the sum of all the primes below n using Sieve of Eratosthenes:
The sieve of Eratosthenes is one of the most efficient ways to find all primes
smaller than n when n is smaller than 10 million. Only for positive numbers.
>>> solution(1000)
76127
>>> solution(5000)
1548136
>>> solution(10000)
5736396
>>> solution(7)
10
>>> solution(7.1) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
>>> solution(-7) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
IndexError: list assignment index out of range
>>> solution("seven") # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: can only concatenate str (not "int") to str
"""
primality_list = [0 for i in range(n + 1)]
primality_list[0] = 1
primality_list[1] = 1
for i in range(2, int(n**0.5) + 1):
if primality_list[i] == 0:
for j in range(i * i, n + 1, i):
primality_list[j] = 1
sum_of_primes = 0
for i in range(n):
if primality_list[i] == 0:
sum_of_primes += i
return sum_of_primes
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_010/sol1.py | project_euler/problem_010/sol1.py | """
Project Euler Problem 10: https://projecteuler.net/problem=10
Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
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.
Returns boolean representing primality of given number num (i.e., if the
result is true, then the number is indeed prime else it is not).
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
>>> is_prime(0)
False
>>> is_prime(1)
False
"""
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(n: int = 2000000) -> int:
"""
Returns the sum of all the primes below n.
>>> solution(1000)
76127
>>> solution(5000)
1548136
>>> solution(10000)
5736396
>>> solution(7)
10
"""
return sum(num for num in range(3, n, 2) if is_prime(num)) + 2 if n > 2 else 0
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_010/__init__.py | project_euler/problem_010/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_064/sol1.py | project_euler/problem_064/sol1.py | """
Project Euler Problem 64: https://projecteuler.net/problem=64
All square roots are periodic when written as continued fractions.
For example, let us consider sqrt(23).
It can be seen that the sequence is repeating.
For conciseness, we use the notation sqrt(23)=[4;(1,3,1,8)],
to indicate that the block (1,3,1,8) repeats indefinitely.
Exactly four continued fractions, for N<=13, have an odd period.
How many continued fractions for N<=10000 have an odd period?
References:
- https://en.wikipedia.org/wiki/Continued_fraction
"""
from math import floor, sqrt
def continuous_fraction_period(n: int) -> int:
"""
Returns the continued fraction period of a number n.
>>> continuous_fraction_period(2)
1
>>> continuous_fraction_period(5)
1
>>> continuous_fraction_period(7)
4
>>> continuous_fraction_period(11)
2
>>> continuous_fraction_period(13)
5
"""
numerator = 0.0
denominator = 1.0
root = int(sqrt(n))
integer_part = root
period = 0
while integer_part != 2 * root:
numerator = denominator * integer_part - numerator
denominator = (n - numerator**2) / denominator
integer_part = int((root + numerator) / denominator)
period += 1
return period
def solution(n: int = 10000) -> int:
"""
Returns the count of numbers <= 10000 with odd periods.
This function calls continuous_fraction_period for numbers which are
not perfect squares.
This is checked in if sr - floor(sr) != 0 statement.
If an odd period is returned by continuous_fraction_period,
count_odd_periods is increased by 1.
>>> solution(2)
1
>>> solution(5)
2
>>> solution(7)
2
>>> solution(11)
3
>>> solution(13)
4
"""
count_odd_periods = 0
for i in range(2, n + 1):
sr = sqrt(i)
if sr - floor(sr) != 0 and continuous_fraction_period(i) % 2 == 1:
count_odd_periods += 1
return count_odd_periods
if __name__ == "__main__":
print(f"{solution(int(input().strip()))}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_064/__init__.py | project_euler/problem_064/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_046/sol1.py | project_euler/problem_046/sol1.py | """
Problem 46: https://projecteuler.net/problem=46
It was proposed by Christian Goldbach that every odd composite number can be
written as the sum of a prime and twice a square.
9 = 7 + 2 x 12
15 = 7 + 2 x 22
21 = 3 + 2 x 32
25 = 7 + 2 x 32
27 = 19 + 2 x 22
33 = 31 + 2 x 12
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a
prime and twice a square?
"""
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
odd_composites = [num for num in range(3, 100001, 2) if not is_prime(num)]
def compute_nums(n: int) -> list[int]:
"""
Returns a list of first n odd composite numbers which do
not follow the conjecture.
>>> compute_nums(1)
[5777]
>>> compute_nums(2)
[5777, 5993]
>>> compute_nums(0)
Traceback (most recent call last):
...
ValueError: n must be >= 0
>>> compute_nums("a")
Traceback (most recent call last):
...
ValueError: n must be an integer
>>> compute_nums(1.1)
Traceback (most recent call last):
...
ValueError: n must be an integer
"""
if not isinstance(n, int):
raise ValueError("n must be an integer")
if n <= 0:
raise ValueError("n must be >= 0")
list_nums = []
for num in range(len(odd_composites)):
i = 0
while 2 * i * i <= odd_composites[num]:
rem = odd_composites[num] - 2 * i * i
if is_prime(rem):
break
i += 1
else:
list_nums.append(odd_composites[num])
if len(list_nums) == n:
return list_nums
return []
def solution() -> int:
"""Return the solution to the problem"""
return compute_nums(1)[0]
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_046/__init__.py | project_euler/problem_046/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_122/sol1.py | project_euler/problem_122/sol1.py | """
Project Euler Problem 122: https://projecteuler.net/problem=122
Efficient Exponentiation
The most naive way of computing n^15 requires fourteen multiplications:
n x n x ... x n = n^15.
But using a "binary" method you can compute it in six multiplications:
n x n = n^2
n^2 x n^2 = n^4
n^4 x n^4 = n^8
n^8 x n^4 = n^12
n^12 x n^2 = n^14
n^14 x n = n^15
However it is yet possible to compute it in only five multiplications:
n x n = n^2
n^2 x n = n^3
n^3 x n^3 = n^6
n^6 x n^6 = n^12
n^12 x n^3 = n^15
We shall define m(k) to be the minimum number of multiplications to compute n^k;
for example m(15) = 5.
Find sum_{k = 1}^200 m(k).
It uses the fact that for rather small n, applicable for this problem, the solution
for each number can be formed by increasing the largest element.
References:
- https://en.wikipedia.org/wiki/Addition_chain
"""
def solve(nums: list[int], goal: int, depth: int) -> bool:
"""
Checks if nums can have a sum equal to goal, given that length of nums does
not exceed depth.
>>> solve([1], 2, 2)
True
>>> solve([1], 2, 0)
False
"""
if len(nums) > depth:
return False
for el in nums:
if el + nums[-1] == goal:
return True
nums.append(el + nums[-1])
if solve(nums=nums, goal=goal, depth=depth):
return True
del nums[-1]
return False
def solution(n: int = 200) -> int:
"""
Calculates sum of smallest number of multiplactions for each number up to
and including n.
>>> solution(1)
0
>>> solution(2)
1
>>> solution(14)
45
>>> solution(15)
50
"""
total = 0
for i in range(2, n + 1):
max_length = 0
while True:
nums = [1]
max_length += 1
if solve(nums=nums, goal=i, depth=max_length):
break
total += max_length
return total
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_122/__init__.py | project_euler/problem_122/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_145/sol1.py | project_euler/problem_145/sol1.py | """
Project Euler problem 145: https://projecteuler.net/problem=145
Author: Vineet Rao, Maxim Smolskiy
Problem statement:
Some positive integers n have the property that the sum [ n + reverse(n) ]
consists entirely of odd (decimal) digits.
For instance, 36 + 63 = 99 and 409 + 904 = 1313.
We will call such numbers reversible; so 36, 63, 409, and 904 are reversible.
Leading zeroes are not allowed in either n or reverse(n).
There are 120 reversible numbers below one-thousand.
How many reversible numbers are there below one-billion (10^9)?
"""
EVEN_DIGITS = [0, 2, 4, 6, 8]
ODD_DIGITS = [1, 3, 5, 7, 9]
def slow_reversible_numbers(
remaining_length: int, remainder: int, digits: list[int], length: int
) -> int:
"""
Count the number of reversible numbers of given length.
Iterate over possible digits considering parity of current sum remainder.
>>> slow_reversible_numbers(1, 0, [0], 1)
0
>>> slow_reversible_numbers(2, 0, [0] * 2, 2)
20
>>> slow_reversible_numbers(3, 0, [0] * 3, 3)
100
"""
if remaining_length == 0:
if digits[0] == 0 or digits[-1] == 0:
return 0
for i in range(length // 2 - 1, -1, -1):
remainder += digits[i] + digits[length - i - 1]
if remainder % 2 == 0:
return 0
remainder //= 10
return 1
if remaining_length == 1:
if remainder % 2 == 0:
return 0
result = 0
for digit in range(10):
digits[length // 2] = digit
result += slow_reversible_numbers(
0, (remainder + 2 * digit) // 10, digits, length
)
return result
result = 0
for digit1 in range(10):
digits[(length + remaining_length) // 2 - 1] = digit1
if (remainder + digit1) % 2 == 0:
other_parity_digits = ODD_DIGITS
else:
other_parity_digits = EVEN_DIGITS
for digit2 in other_parity_digits:
digits[(length - remaining_length) // 2] = digit2
result += slow_reversible_numbers(
remaining_length - 2,
(remainder + digit1 + digit2) // 10,
digits,
length,
)
return result
def slow_solution(max_power: int = 9) -> int:
"""
To evaluate the solution, use solution()
>>> slow_solution(3)
120
>>> slow_solution(6)
18720
>>> slow_solution(7)
68720
"""
result = 0
for length in range(1, max_power + 1):
result += slow_reversible_numbers(length, 0, [0] * length, length)
return result
def reversible_numbers(
remaining_length: int, remainder: int, digits: list[int], length: int
) -> int:
"""
Count the number of reversible numbers of given length.
Iterate over possible digits considering parity of current sum remainder.
>>> reversible_numbers(1, 0, [0], 1)
0
>>> reversible_numbers(2, 0, [0] * 2, 2)
20
>>> reversible_numbers(3, 0, [0] * 3, 3)
100
"""
# There exist no reversible 1, 5, 9, 13 (ie. 4k+1) digit numbers
if (length - 1) % 4 == 0:
return 0
return slow_reversible_numbers(remaining_length, remainder, digits, length)
def solution(max_power: int = 9) -> int:
"""
To evaluate the solution, use solution()
>>> solution(3)
120
>>> solution(6)
18720
>>> solution(7)
68720
"""
result = 0
for length in range(1, max_power + 1):
result += reversible_numbers(length, 0, [0] * length, length)
return result
def benchmark() -> None:
"""
Benchmarks
"""
# Running performance benchmarks...
# slow_solution : 292.9300301000003
# solution : 54.90970860000016
from timeit import timeit
print("Running performance benchmarks...")
print(f"slow_solution : {timeit('slow_solution()', globals=globals(), number=10)}")
print(f"solution : {timeit('solution()', globals=globals(), number=10)}")
if __name__ == "__main__":
print(f"Solution : {solution()}")
benchmark()
# for i in range(1, 15):
# print(f"{i}. {reversible_numbers(i, 0, [0]*i, i)}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_145/__init__.py | project_euler/problem_145/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_031/sol2.py | project_euler/problem_031/sol2.py | """
Problem 31: https://projecteuler.net/problem=31
Coin sums
In England the currency is made up of pound, f, and pence, p, and there are
eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, f1 (100p) and f2 (200p).
It is possible to make f2 in the following way:
1xf1 + 1x50p + 2x20p + 1x5p + 1x2p + 3x1p
How many different ways can f2 be made using any number of coins?
Hint:
> There are 100 pence in a pound (f1 = 100p)
> There are coins(in pence) are available: 1, 2, 5, 10, 20, 50, 100 and 200.
> how many different ways you can combine these values to create 200 pence.
Example:
to make 6p there are 5 ways
1,1,1,1,1,1
1,1,1,1,2
1,1,2,2
2,2,2
1,5
to make 5p there are 4 ways
1,1,1,1,1
1,1,1,2
1,2,2
5
"""
def solution(pence: int = 200) -> int:
"""Returns the number of different ways to make X pence using any number of coins.
The solution is based on dynamic programming paradigm in a bottom-up fashion.
>>> solution(500)
6295434
>>> solution(200)
73682
>>> solution(50)
451
>>> solution(10)
11
"""
coins = [1, 2, 5, 10, 20, 50, 100, 200]
number_of_ways = [0] * (pence + 1)
number_of_ways[0] = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(coin, pence + 1, 1):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73682
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_031/sol1.py | project_euler/problem_031/sol1.py | """
Coin sums
Problem 31: https://projecteuler.net/problem=31
In England the currency is made up of pound, f, and pence, p, and there are
eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, f1 (100p) and f2 (200p).
It is possible to make f2 in the following way:
1xf1 + 1x50p + 2x20p + 1x5p + 1x2p + 3x1p
How many different ways can f2 be made using any number of coins?
"""
def one_pence() -> int:
return 1
def two_pence(x: int) -> int:
return 0 if x < 0 else two_pence(x - 2) + one_pence()
def five_pence(x: int) -> int:
return 0 if x < 0 else five_pence(x - 5) + two_pence(x)
def ten_pence(x: int) -> int:
return 0 if x < 0 else ten_pence(x - 10) + five_pence(x)
def twenty_pence(x: int) -> int:
return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x)
def fifty_pence(x: int) -> int:
return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x)
def one_pound(x: int) -> int:
return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x)
def two_pound(x: int) -> int:
return 0 if x < 0 else two_pound(x - 200) + one_pound(x)
def solution(n: int = 200) -> int:
"""Returns the number of different ways can n pence be made using any number of
coins?
>>> solution(500)
6295434
>>> solution(200)
73682
>>> solution(50)
451
>>> solution(10)
11
"""
return two_pound(n)
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_031/__init__.py | project_euler/problem_031/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_190/sol1.py | project_euler/problem_190/sol1.py | """
Project Euler Problem 190: https://projecteuler.net/problem=190
Maximising a Weighted Product
Let S_m = (x_1, x_2, ..., x_m) be the m-tuple of positive real numbers with
x_1 + x_2 + ... + x_m = m for which P_m = x_1 * x_2^2 * ... * x_m^m is maximised.
For example, it can be verified that |_ P_10 _| = 4112
(|_ _| is the integer part function).
Find Sum_{m=2}^15 = |_ P_m _|.
Solution:
- Fix x_1 = m - x_2 - ... - x_m.
- Calculate partial derivatives of P_m wrt the x_2, ..., x_m. This gives that
x_2 = 2 * x_1, x_3 = 3 * x_1, ..., x_m = m * x_1.
- Calculate partial second order derivatives of P_m wrt the x_2, ..., x_m.
By plugging in the values from the previous step, can verify that solution is maximum.
"""
def solution(n: int = 15) -> int:
"""
Calculate sum of |_ P_m _| for m from 2 to n.
>>> solution(2)
1
>>> solution(3)
2
>>> solution(4)
4
>>> solution(5)
10
"""
total = 0
for m in range(2, n + 1):
x1 = 2 / (m + 1)
p = 1.0
for i in range(1, m + 1):
xi = i * x1
p *= xi**i
total += int(p)
return total
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_190/__init__.py | project_euler/problem_190/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_005/sol2.py | project_euler/problem_005/sol2.py | from maths.greatest_common_divisor import greatest_common_divisor
"""
Project Euler Problem 5: https://projecteuler.net/problem=5
Smallest multiple
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is _evenly divisible_ by all
of the numbers from 1 to 20?
References:
- https://en.wiktionary.org/wiki/evenly_divisible
- https://en.wikipedia.org/wiki/Euclidean_algorithm
- https://en.wikipedia.org/wiki/Least_common_multiple
"""
def lcm(x: int, y: int) -> int:
"""
Least Common Multiple.
Using the property that lcm(a, b) * greatest_common_divisor(a, b) = a*b
>>> lcm(3, 15)
15
>>> lcm(1, 27)
27
>>> lcm(13, 27)
351
>>> lcm(64, 48)
192
"""
return (x * y) // greatest_common_divisor(x, y)
def solution(n: int = 20) -> int:
"""
Returns the smallest positive number that is evenly divisible (divisible
with no remainder) by all of the numbers from 1 to n.
>>> solution(10)
2520
>>> solution(15)
360360
>>> solution(22)
232792560
"""
g = 1
for i in range(1, n + 1):
g = lcm(g, i)
return g
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_005/sol1.py | project_euler/problem_005/sol1.py | """
Project Euler Problem 5: https://projecteuler.net/problem=5
Smallest multiple
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is _evenly divisible_ by all
of the numbers from 1 to 20?
References:
- https://en.wiktionary.org/wiki/evenly_divisible
"""
def solution(n: int = 20) -> int:
"""
Returns the smallest positive number that is evenly divisible (divisible
with no remainder) by all of the numbers from 1 to n.
>>> solution(10)
2520
>>> solution(15)
360360
>>> solution(22)
232792560
>>> solution(3.4)
6
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution(-17)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution([])
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
>>> solution("asd")
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
"""
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
i = 0
while 1:
i += n * (n - 1)
nfound = 0
for j in range(2, n):
if i % j != 0:
nfound = 1
break
if nfound == 0:
if i == 0:
i = 1
return i
return None
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_005/__init__.py | project_euler/problem_005/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_180/sol1.py | project_euler/problem_180/sol1.py | """
Project Euler Problem 234: https://projecteuler.net/problem=234
For any integer n, consider the three functions
f1,n(x,y,z) = x^(n+1) + y^(n+1) - z^(n+1)
f2,n(x,y,z) = (xy + yz + zx)*(x^(n-1) + y^(n-1) - z^(n-1))
f3,n(x,y,z) = xyz*(xn-2 + yn-2 - zn-2)
and their combination
fn(x,y,z) = f1,n(x,y,z) + f2,n(x,y,z) - f3,n(x,y,z)
We call (x,y,z) a golden triple of order k if x, y, and z are all rational numbers
of the form a / b with 0 < a < b β€ k and there is (at least) one integer n,
so that fn(x,y,z) = 0.
Let s(x,y,z) = x + y + z.
Let t = u / v be the sum of all distinct s(x,y,z) for all golden triples
(x,y,z) of order 35.
All the s(x,y,z) and t must be in reduced form.
Find u + v.
Solution:
By expanding the brackets it is easy to show that
fn(x, y, z) = (x + y + z) * (x^n + y^n - z^n).
Since x,y,z are positive, the requirement fn(x, y, z) = 0 is fulfilled if and
only if x^n + y^n = z^n.
By Fermat's Last Theorem, this means that the absolute value of n can not
exceed 2, i.e. n is in {-2, -1, 0, 1, 2}. We can eliminate n = 0 since then the
equation would reduce to 1 + 1 = 1, for which there are no solutions.
So all we have to do is iterate through the possible numerators and denominators
of x and y, calculate the corresponding z, and check if the corresponding numerator and
denominator are integer and satisfy 0 < z_num < z_den <= 0. We use a set "uniquq_s"
to make sure there are no duplicates, and the fractions.Fraction class to make sure
we get the right numerator and denominator.
Reference:
https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem
"""
from __future__ import annotations
from fractions import Fraction
from math import gcd, sqrt
def is_sq(number: int) -> bool:
"""
Check if number is a perfect square.
>>> is_sq(1)
True
>>> is_sq(1000001)
False
>>> is_sq(1000000)
True
"""
sq: int = int(number**0.5)
return number == sq * sq
def add_three(
x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int
) -> tuple[int, int]:
"""
Given the numerators and denominators of three fractions, return the
numerator and denominator of their sum in lowest form.
>>> add_three(1, 3, 1, 3, 1, 3)
(1, 1)
>>> add_three(2, 5, 4, 11, 12, 3)
(262, 55)
"""
top: int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
bottom: int = x_den * y_den * z_den
hcf: int = gcd(top, bottom)
top //= hcf
bottom //= hcf
return top, bottom
def solution(order: int = 35) -> int:
"""
Find the sum of the numerator and denominator of the sum of all s(x,y,z) for
golden triples (x,y,z) of the given order.
>>> solution(5)
296
>>> solution(10)
12519
>>> solution(20)
19408891927
"""
unique_s: set = set()
hcf: int
total: Fraction = Fraction(0)
fraction_sum: tuple[int, int]
for x_num in range(1, order + 1):
for x_den in range(x_num + 1, order + 1):
for y_num in range(1, order + 1):
for y_den in range(y_num + 1, order + 1):
# n=1
z_num = x_num * y_den + x_den * y_num
z_den = x_den * y_den
hcf = gcd(z_num, z_den)
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
fraction_sum = add_three(
x_num, x_den, y_num, y_den, z_num, z_den
)
unique_s.add(fraction_sum)
# n=2
z_num = (
x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
)
z_den = x_den * x_den * y_den * y_den
if is_sq(z_num) and is_sq(z_den):
z_num = int(sqrt(z_num))
z_den = int(sqrt(z_den))
hcf = gcd(z_num, z_den)
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
fraction_sum = add_three(
x_num, x_den, y_num, y_den, z_num, z_den
)
unique_s.add(fraction_sum)
# n=-1
z_num = x_num * y_num
z_den = x_den * y_num + x_num * y_den
hcf = gcd(z_num, z_den)
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
fraction_sum = add_three(
x_num, x_den, y_num, y_den, z_num, z_den
)
unique_s.add(fraction_sum)
# n=2
z_num = x_num * x_num * y_num * y_num
z_den = (
x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
)
if is_sq(z_num) and is_sq(z_den):
z_num = int(sqrt(z_num))
z_den = int(sqrt(z_den))
hcf = gcd(z_num, z_den)
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
fraction_sum = add_three(
x_num, x_den, y_num, y_den, z_num, z_den
)
unique_s.add(fraction_sum)
for num, den in unique_s:
total += Fraction(num, den)
return total.denominator + total.numerator
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_180/__init__.py | project_euler/problem_180/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_091/sol1.py | project_euler/problem_091/sol1.py | """
Project Euler Problem 91: https://projecteuler.net/problem=91
The points P (x1, y1) and Q (x2, y2) are plotted at integer coordinates and
are joined to the origin, O(0,0), to form ΞOPQ.
οΏΌ
There are exactly fourteen triangles containing a right angle that can be formed
when each coordinate lies between 0 and 2 inclusive; that is,
0 β€ x1, y1, x2, y2 β€ 2.
οΏΌ
Given that 0 β€ x1, y1, x2, y2 β€ 50, how many right triangles can be formed?
"""
from itertools import combinations, product
def is_right(x1: int, y1: int, x2: int, y2: int) -> bool:
"""
Check if the triangle described by P(x1,y1), Q(x2,y2) and O(0,0) is right-angled.
Note: this doesn't check if P and Q are equal, but that's handled by the use of
itertools.combinations in the solution function.
>>> is_right(0, 1, 2, 0)
True
>>> is_right(1, 0, 2, 2)
False
"""
if x1 == y1 == 0 or x2 == y2 == 0:
return False
a_square = x1 * x1 + y1 * y1
b_square = x2 * x2 + y2 * y2
c_square = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
return (
a_square + b_square == c_square
or a_square + c_square == b_square
or b_square + c_square == a_square
)
def solution(limit: int = 50) -> int:
"""
Return the number of right triangles OPQ that can be formed by two points P, Q
which have both x- and y- coordinates between 0 and limit inclusive.
>>> solution(2)
14
>>> solution(10)
448
"""
return sum(
1
for pt1, pt2 in combinations(product(range(limit + 1), repeat=2), 2)
if is_right(*pt1, *pt2)
)
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_091/__init__.py | project_euler/problem_091/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_075/sol1.py | project_euler/problem_075/sol1.py | """
Project Euler Problem 75: https://projecteuler.net/problem=75
It turns out that 12 cm is the smallest length of wire that can be bent to form an
integer sided right angle triangle in exactly one way, but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided
right angle triangle, and other lengths allow more than one solution to be found; for
example, using 120 cm it is possible to form exactly three different integer sided
right angle triangles.
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L β€ 1,500,000 can
exactly one integer sided right angle triangle be formed?
Solution: we generate all pythagorean triples using Euclid's formula and
keep track of the frequencies of the perimeters.
Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
"""
from collections import defaultdict
from math import gcd
def solution(limit: int = 1500000) -> int:
"""
Return the number of values of L <= limit such that a wire of length L can be
formmed into an integer sided right angle triangle in exactly one way.
>>> solution(50)
6
>>> solution(1000)
112
>>> solution(50000)
5502
"""
frequencies: defaultdict = defaultdict(int)
euclid_m = 2
while 2 * euclid_m * (euclid_m + 1) <= limit:
for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2):
if gcd(euclid_m, euclid_n) > 1:
continue
primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n)
for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter):
frequencies[perimeter] += 1
euclid_m += 1
return sum(1 for frequency in frequencies.values() if frequency == 1)
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_075/__init__.py | project_euler/problem_075/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_003/sol2.py | project_euler/problem_003/sol2.py | """
Project Euler Problem 3: https://projecteuler.net/problem=3
Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
References:
- https://en.wikipedia.org/wiki/Prime_number#Unique_factorization
"""
def solution(n: int = 600851475143) -> int:
"""
Returns the largest prime factor of a given number n.
>>> solution(13195)
29
>>> solution(10)
5
>>> solution(17)
17
>>> solution(3.4)
3
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution(-17)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution([])
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
>>> solution("asd")
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
"""
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
prime = 1
i = 2
while i * i <= n:
while n % i == 0:
prime = i
n //= i
i += 1
if n > 1:
prime = n
return int(prime)
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_003/sol3.py | project_euler/problem_003/sol3.py | """
Project Euler Problem 3: https://projecteuler.net/problem=3
Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
References:
- https://en.wikipedia.org/wiki/Prime_number#Unique_factorization
"""
def solution(n: int = 600851475143) -> int:
"""
Returns the largest prime factor of a given number n.
>>> solution(13195)
29
>>> solution(10)
5
>>> solution(17)
17
>>> solution(3.4)
3
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution(-17)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution([])
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
>>> solution("asd")
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
"""
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
i = 2
ans = 0
if n == 2:
return 2
while n > 2:
while n % i != 0:
i += 1
ans = i
while n % i == 0:
n = n // i
i += 1
return int(ans)
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_003/sol1.py | project_euler/problem_003/sol1.py | """
Project Euler Problem 3: https://projecteuler.net/problem=3
Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
References:
- https://en.wikipedia.org/wiki/Prime_number#Unique_factorization
"""
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.
Returns boolean representing primality of given number (i.e., if the
result is true, then the number is indeed prime else it is not).
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(2999)
True
>>> is_prime(0)
False
>>> is_prime(1)
False
"""
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(n: int = 600851475143) -> int:
"""
Returns the largest prime factor of a given number n.
>>> solution(13195)
29
>>> solution(10)
5
>>> solution(17)
17
>>> solution(3.4)
3
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution(-17)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution([])
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
>>> solution("asd")
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
"""
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
max_number = 0
if is_prime(n):
return n
while n % 2 == 0:
n //= 2
if is_prime(n):
return n
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
if is_prime(n // i):
max_number = n // i
break
elif is_prime(i):
max_number = i
return max_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_003/__init__.py | project_euler/problem_003/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_086/sol1.py | project_euler/problem_086/sol1.py | """
Project Euler Problem 86: https://projecteuler.net/problem=86
A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a fly, F,
sits in the opposite corner. By travelling on the surfaces of the room the shortest
"straight line" distance from S to F is 10 and the path is shown on the diagram.
οΏΌ
However, there are up to three "shortest" path candidates for any given cuboid and the
shortest route doesn't always have integer length.
It can be shown that there are exactly 2060 distinct cuboids, ignoring rotations, with
integer dimensions, up to a maximum size of M by M by M, for which the shortest route
has integer length when M = 100. This is the least value of M for which the number of
solutions first exceeds two thousand; the number of solutions when M = 99 is 1975.
Find the least value of M such that the number of solutions first exceeds one million.
Solution:
Label the 3 side-lengths of the cuboid a,b,c such that 1 <= a <= b <= c <= M.
By conceptually "opening up" the cuboid and laying out its faces on a plane,
it can be seen that the shortest distance between 2 opposite corners is
sqrt((a+b)^2 + c^2). This distance is an integer if and only if (a+b),c make up
the first 2 sides of a pythagorean triplet.
The second useful insight is rather than calculate the number of cuboids
with integral shortest distance for each maximum cuboid side-length M,
we can calculate this number iteratively each time we increase M, as follows.
The set of cuboids satisfying this property with maximum side-length M-1 is a
subset of the cuboids satisfying the property with maximum side-length M
(since any cuboids with side lengths <= M-1 are also <= M). To calculate the
number of cuboids in the larger set (corresponding to M) we need only consider
the cuboids which have at least one side of length M. Since we have ordered the
side lengths a <= b <= c, we can assume that c = M. Then we just need to count
the number of pairs a,b satisfying the conditions:
sqrt((a+b)^2 + M^2) is integer
1 <= a <= b <= M
To count the number of pairs (a,b) satisfying these conditions, write d = a+b.
Now we have:
1 <= a <= b <= M => 2 <= d <= 2*M
we can actually make the second equality strict,
since d = 2*M => d^2 + M^2 = 5M^2
=> shortest distance = M * sqrt(5)
=> not integral.
a + b = d => b = d - a
and a <= b
=> a <= d/2
also a <= M
=> a <= min(M, d//2)
a + b = d => a = d - b
and b <= M
=> a >= d - M
also a >= 1
=> a >= max(1, d - M)
So a is in range(max(1, d - M), min(M, d // 2) + 1)
For a given d, the number of cuboids satisfying the required property with c = M
and a + b = d is the length of this range, which is
min(M, d // 2) + 1 - max(1, d - M).
In the code below, d is sum_shortest_sides
and M is max_cuboid_size.
"""
from math import sqrt
def solution(limit: int = 1000000) -> int:
"""
Return the least value of M such that there are more than one million cuboids
of side lengths 1 <= a,b,c <= M such that the shortest distance between two
opposite vertices of the cuboid is integral.
>>> solution(100)
24
>>> solution(1000)
72
>>> solution(2000)
100
>>> solution(20000)
288
"""
num_cuboids: int = 0
max_cuboid_size: int = 0
sum_shortest_sides: int
while num_cuboids <= limit:
max_cuboid_size += 1
for sum_shortest_sides in range(2, 2 * max_cuboid_size + 1):
if sqrt(sum_shortest_sides**2 + max_cuboid_size**2).is_integer():
num_cuboids += (
min(max_cuboid_size, sum_shortest_sides // 2)
- max(1, sum_shortest_sides - max_cuboid_size)
+ 1
)
return max_cuboid_size
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_086/__init__.py | project_euler/problem_086/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_206/sol1.py | project_euler/problem_206/sol1.py | """
Project Euler Problem 206: https://projecteuler.net/problem=206
Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,
where each β_β is a single digit.
-----
Instead of computing every single permutation of that number and going
through a 10^9 search space, we can narrow it down considerably.
If the square ends in a 0, then the square root must also end in a 0. Thus,
the last missing digit must be 0 and the square root is a multiple of 10.
We can narrow the search space down to the first 8 digits and multiply the
result of that by 10 at the end.
Now the last digit is a 9, which can only happen if the square root ends
in a 3 or 7. From this point, we can try one of two different methods to find
the answer:
1. Start at the lowest possible base number whose square would be in the
format, and count up. The base we would start at is 101010103, whose square is
the closest number to 10203040506070809. Alternate counting up by 4 and 6 so
the last digit of the base is always a 3 or 7.
2. Start at the highest possible base number whose square would be in the
format, and count down. That base would be 138902663, whose square is the
closest number to 1929394959697989. Alternate counting down by 6 and 4 so the
last digit of the base is always a 3 or 7.
The solution does option 2 because the answer happens to be much closer to the
starting point.
"""
def is_square_form(num: int) -> bool:
"""
Determines if num is in the form 1_2_3_4_5_6_7_8_9
>>> is_square_form(1)
False
>>> is_square_form(112233445566778899)
True
>>> is_square_form(123456789012345678)
False
"""
digit = 9
while num > 0:
if num % 10 != digit:
return False
num //= 100
digit -= 1
return True
def solution() -> int:
"""
Returns the first integer whose square is of the form 1_2_3_4_5_6_7_8_9_0
"""
num = 138902663
while not is_square_form(num * num):
if num % 10 == 3:
num -= 6 # (3 - 6) % 10 = 7
else:
num -= 4 # (7 - 4) % 10 = 3
return num * 10
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_206/__init__.py | project_euler/problem_206/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_059/sol1.py | project_euler/problem_059/sol1.py | """
Each character on a computer is assigned a unique code and the preferred standard is
ASCII (American Standard Code for Information Interchange).
For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to ASCII, then
XOR each byte with a given value, taken from a secret key. The advantage with the
XOR function is that using the same encryption key on the cipher text, restores
the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text message, and
the key is made up of random bytes. The user would keep the encrypted message and the
encryption key in different locations, and without both "halves", it is impossible to
decrypt the message.
Unfortunately, this method is impractical for most users, so the modified method is
to use a password as a key. If the password is shorter than the message, which is
likely, the key is repeated cyclically throughout the message. The balance for this
method is using a sufficiently long password key for security, but short enough to
be memorable.
Your task has been made easy, as the encryption key consists of three lower case
characters. Using p059_cipher.txt (right click and 'Save Link/Target As...'), a
file containing the encrypted ASCII codes, and the knowledge that the plain text
must contain common English words, decrypt the message and find the sum of the ASCII
values in the original text.
"""
from __future__ import annotations
import string
from itertools import cycle, product
from pathlib import Path
VALID_CHARS: str = (
string.ascii_letters + string.digits + string.punctuation + string.whitespace
)
LOWERCASE_INTS: list[int] = [ord(letter) for letter in string.ascii_lowercase]
VALID_INTS: set[int] = {ord(char) for char in VALID_CHARS}
COMMON_WORDS: list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"]
def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None:
"""
Given an encrypted message and a possible 3-character key, decrypt the message.
If the decrypted message contains a invalid character, i.e. not an ASCII letter,
a digit, punctuation or whitespace, then we know the key is incorrect, so return
None.
>>> try_key([0, 17, 20, 4, 27], (104, 116, 120))
'hello'
>>> try_key([68, 10, 300, 4, 27], (104, 116, 120)) is None
True
"""
decoded: str = ""
keychar: int
cipherchar: int
decodedchar: int
for keychar, cipherchar in zip(cycle(key), ciphertext):
decodedchar = cipherchar ^ keychar
if decodedchar not in VALID_INTS:
return None
decoded += chr(decodedchar)
return decoded
def filter_valid_chars(ciphertext: list[int]) -> list[str]:
"""
Given an encrypted message, test all 3-character strings to try and find the
key. Return a list of the possible decrypted messages.
>>> from itertools import cycle
>>> text = "The enemy's gate is down"
>>> key = "end"
>>> encoded = [ord(k) ^ ord(c) for k,c in zip(cycle(key), text)]
>>> text in filter_valid_chars(encoded)
True
"""
possibles: list[str] = []
for key in product(LOWERCASE_INTS, repeat=3):
encoded = try_key(ciphertext, key)
if encoded is not None:
possibles.append(encoded)
return possibles
def filter_common_word(possibles: list[str], common_word: str) -> list[str]:
"""
Given a list of possible decoded messages, narrow down the possibilities
for checking for the presence of a specified common word. Only decoded messages
containing common_word will be returned.
>>> filter_common_word(['asfla adf', 'I am here', ' !?! #a'], 'am')
['I am here']
>>> filter_common_word(['athla amf', 'I am here', ' !?! #a'], 'am')
['athla amf', 'I am here']
"""
return [possible for possible in possibles if common_word in possible.lower()]
def solution(filename: str = "p059_cipher.txt") -> int:
"""
Test the ciphertext against all possible 3-character keys, then narrow down the
possibilities by filtering using common words until there's only one possible
decoded message.
>>> solution("test_cipher.txt")
3000
"""
ciphertext: list[int]
possibles: list[str]
common_word: str
decoded_text: str
data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8")
ciphertext = [int(number) for number in data.strip().split(",")]
possibles = filter_valid_chars(ciphertext)
for common_word in COMMON_WORDS:
possibles = filter_common_word(possibles, common_word)
if len(possibles) == 1:
break
decoded_text = possibles[0]
return sum(ord(char) for char in decoded_text)
if __name__ == "__main__":
print(f"{solution() = }")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_059/__init__.py | project_euler/problem_059/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_048/sol1.py | project_euler/problem_048/sol1.py | """
Self Powers
Problem 48
The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
"""
def solution():
"""
Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
>>> solution()
'9110846700'
"""
total = 0
for i in range(1, 1001):
total += i**i
return str(total)[-10:]
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_048/__init__.py | project_euler/problem_048/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_074/sol2.py | project_euler/problem_074/sol2.py | """
Project Euler Problem 074: https://projecteuler.net/problem=74
The number 145 is well known for the property that the sum of the factorial of its
digits is equal to 145:
1! + 4! + 5! = 1 + 24 + 120 = 145
Perhaps less well known is 169, in that it produces the longest chain of numbers that
link back to 169; it turns out that there are only three such loops that exist:
169 β 363601 β 1454 β 169
871 β 45361 β 871
872 β 45362 β 872
It is not difficult to prove that EVERY starting number will eventually get stuck in a
loop. For example,
69 β 363600 β 1454 β 169 β 363601 (β 1454)
78 β 45360 β 871 β 45361 (β 871)
540 β 145 (β 145)
Starting with 69 produces a chain of five non-repeating terms, but the longest
non-repeating chain with a starting number below one million is sixty terms.
How many chains, with a starting number below one million, contain exactly sixty
non-repeating terms?
Solution approach:
This solution simply consists in a loop that generates the chains of non repeating
items using the cached sizes of the previous chains.
The generation of the chain stops before a repeating item or if the size of the chain
is greater then the desired one.
After generating each chain, the length is checked and the counter increases.
"""
from math import factorial
DIGIT_FACTORIAL: dict[str, int] = {str(digit): factorial(digit) for digit in range(10)}
def digit_factorial_sum(number: int) -> int:
"""
Function to perform the sum of the factorial of all the digits in number
>>> digit_factorial_sum(69.0)
Traceback (most recent call last):
...
TypeError: Parameter number must be int
>>> digit_factorial_sum(-1)
Traceback (most recent call last):
...
ValueError: Parameter number must be greater than or equal to 0
>>> digit_factorial_sum(0)
1
>>> digit_factorial_sum(69)
363600
"""
if not isinstance(number, int):
raise TypeError("Parameter number must be int")
if number < 0:
raise ValueError("Parameter number must be greater than or equal to 0")
# Converts number in string to iterate on its digits and adds its factorial.
return sum(DIGIT_FACTORIAL[digit] for digit in str(number))
def solution(chain_length: int = 60, number_limit: int = 1000000) -> int:
"""
Returns the number of numbers below number_limit that produce chains with exactly
chain_length non repeating elements.
>>> solution(10.0, 1000)
Traceback (most recent call last):
...
TypeError: Parameters chain_length and number_limit must be int
>>> solution(10, 1000.0)
Traceback (most recent call last):
...
TypeError: Parameters chain_length and number_limit must be int
>>> solution(0, 1000)
Traceback (most recent call last):
...
ValueError: Parameters chain_length and number_limit must be greater than 0
>>> solution(10, 0)
Traceback (most recent call last):
...
ValueError: Parameters chain_length and number_limit must be greater than 0
>>> solution(10, 1000)
26
"""
if not isinstance(chain_length, int) or not isinstance(number_limit, int):
raise TypeError("Parameters chain_length and number_limit must be int")
if chain_length <= 0 or number_limit <= 0:
raise ValueError(
"Parameters chain_length and number_limit must be greater than 0"
)
# the counter for the chains with the exact desired length
chains_counter = 0
# the cached sizes of the previous chains
chain_sets_lengths: dict[int, int] = {}
for start_chain_element in range(1, number_limit):
# The temporary set will contain the elements of the chain
chain_set = set()
chain_set_length = 0
# Stop computing the chain when you find a cached size, a repeating item or the
# length is greater then the desired one.
chain_element = start_chain_element
while (
chain_element not in chain_sets_lengths
and chain_element not in chain_set
and chain_set_length <= chain_length
):
chain_set.add(chain_element)
chain_set_length += 1
chain_element = digit_factorial_sum(chain_element)
if chain_element in chain_sets_lengths:
chain_set_length += chain_sets_lengths[chain_element]
chain_sets_lengths[start_chain_element] = chain_set_length
# If chain contains the exact amount of elements increase the counter
if chain_set_length == chain_length:
chains_counter += 1
return chains_counter
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_074/sol1.py | project_euler/problem_074/sol1.py | """
Project Euler Problem 74: https://projecteuler.net/problem=74
The number 145 is well known for the property that the sum of the factorial of its
digits is equal to 145:
1! + 4! + 5! = 1 + 24 + 120 = 145
Perhaps less well known is 169, in that it produces the longest chain of numbers that
link back to 169; it turns out that there are only three such loops that exist:
169 β 363601 β 1454 β 169
871 β 45361 β 871
872 β 45362 β 872
It is not difficult to prove that EVERY starting number will eventually get stuck in
a loop. For example,
69 β 363600 β 1454 β 169 β 363601 (β 1454)
78 β 45360 β 871 β 45361 (β 871)
540 β 145 (β 145)
Starting with 69 produces a chain of five non-repeating terms, but the longest
non-repeating chain with a starting number below one million is sixty terms.
How many chains, with a starting number below one million, contain exactly sixty
non-repeating terms?
"""
DIGIT_FACTORIALS = {
"0": 1,
"1": 1,
"2": 2,
"3": 6,
"4": 24,
"5": 120,
"6": 720,
"7": 5040,
"8": 40320,
"9": 362880,
}
CACHE_SUM_DIGIT_FACTORIALS = {145: 145}
CHAIN_LENGTH_CACHE = {
145: 0,
169: 3,
36301: 3,
1454: 3,
871: 2,
45361: 2,
872: 2,
}
def sum_digit_factorials(n: int) -> int:
"""
Return the sum of the factorial of the digits of n.
>>> sum_digit_factorials(145)
145
>>> sum_digit_factorials(45361)
871
>>> sum_digit_factorials(540)
145
"""
if n in CACHE_SUM_DIGIT_FACTORIALS:
return CACHE_SUM_DIGIT_FACTORIALS[n]
ret = sum(DIGIT_FACTORIALS[let] for let in str(n))
CACHE_SUM_DIGIT_FACTORIALS[n] = ret
return ret
def chain_length(n: int, previous: set | None = None) -> int:
"""
Calculate the length of the chain of non-repeating terms starting with n.
Previous is a set containing the previous member of the chain.
>>> chain_length(10101)
11
>>> chain_length(555)
20
>>> chain_length(178924)
39
"""
previous = previous or set()
if n in CHAIN_LENGTH_CACHE:
return CHAIN_LENGTH_CACHE[n]
next_number = sum_digit_factorials(n)
if next_number in previous:
CHAIN_LENGTH_CACHE[n] = 0
return 0
else:
previous.add(n)
ret = 1 + chain_length(next_number, previous)
CHAIN_LENGTH_CACHE[n] = ret
return ret
def solution(num_terms: int = 60, max_start: int = 1000000) -> int:
"""
Return the number of chains with a starting number below one million which
contain exactly n non-repeating terms.
>>> solution(10,1000)
28
"""
return sum(1 for i in range(1, max_start) if chain_length(i) == num_terms)
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_074/__init__.py | project_euler/problem_074/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_013/sol1.py | project_euler/problem_013/sol1.py | """
Problem 13: https://projecteuler.net/problem=13
Problem Statement:
Work out the first ten digits of the sum of the following one-hundred 50-digit
numbers.
"""
import os
def solution():
"""
Returns the first ten digits of the sum of the array elements
from the file num.txt
>>> solution()
'5537376230'
"""
file_path = os.path.join(os.path.dirname(__file__), "num.txt")
with open(file_path) as file_hand:
return str(sum(int(line) for line in file_hand))[:10]
if __name__ == "__main__":
print(solution())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_013/__init__.py | project_euler/problem_013/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_022/sol2.py | project_euler/problem_022/sol2.py | """
Name scores
Problem 22
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
containing over five-thousand first names, begin by sorting it into
alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a name
score.
For example, when the list is sorted into alphabetical order, COLIN, which is
worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
obtain a score of 938 x 53 = 49714.
What is the total of all the name scores in the file?
"""
import os
def solution():
"""Returns the total of all the name scores in the file.
>>> solution()
871198282
"""
total_sum = 0
temp_sum = 0
with open(os.path.dirname(__file__) + "/p022_names.txt") as file:
name = str(file.readlines()[0])
name = name.replace('"', "").split(",")
name.sort()
for i in range(len(name)):
for j in name[i]:
temp_sum += ord(j) - ord("A") + 1
total_sum += (i + 1) * temp_sum
temp_sum = 0
return total_sum
if __name__ == "__main__":
print(solution())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/project_euler/problem_022/sol1.py | project_euler/problem_022/sol1.py | """
Name scores
Problem 22
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
containing over five-thousand first names, begin by sorting it into
alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a name
score.
For example, when the list is sorted into alphabetical order, COLIN, which is
worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
obtain a score of 938 x 53 = 49714.
What is the total of all the name scores in the file?
"""
import os
def solution():
"""Returns the total of all the name scores in the file.
>>> solution()
871198282
"""
with open(os.path.dirname(__file__) + "/p022_names.txt") as file:
names = str(file.readlines()[0])
names = names.replace('"', "").split(",")
names.sort()
name_score = 0
total_score = 0
for i, name in enumerate(names):
for letter in name:
name_score += ord(letter) - 64
total_score += (i + 1) * name_score
name_score = 0
return total_score
if __name__ == "__main__":
print(solution())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.