Skip to content

Commit 9971f98

Browse files
authored
Added solution for Project Euler problem 87. (TheAlgorithms#3141)
* Added solution for Project Euler problem 87. Fixes: TheAlgorithms#2695 * Update docstring and 0-padding in directory name. Reference: TheAlgorithms#3256
1 parent a1e9656 commit 9971f98

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

project_euler/problem_087/__init__.py

Whitespace-only changes.

project_euler/problem_087/sol1.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
Project Euler Problem 87: https://projecteuler.net/problem=87
3+
4+
The smallest number expressible as the sum of a prime square, prime cube, and prime
5+
fourth power is 28. In fact, there are exactly four numbers below fifty that can be
6+
expressed in such a way:
7+
8+
28 = 22 + 23 + 24
9+
33 = 32 + 23 + 24
10+
49 = 52 + 23 + 24
11+
47 = 22 + 33 + 24
12+
13+
How many numbers below fifty million can be expressed as the sum of a prime square,
14+
prime cube, and prime fourth power?
15+
"""
16+
17+
18+
def solution(limit: int = 50000000) -> int:
19+
"""
20+
Return the number of integers less than limit which can be expressed as the sum
21+
of a prime square, prime cube, and prime fourth power.
22+
>>> solution(50)
23+
4
24+
"""
25+
ret = set()
26+
prime_square_limit = int((limit - 24) ** (1 / 2))
27+
28+
primes = set(range(3, prime_square_limit + 1, 2))
29+
primes.add(2)
30+
for p in range(3, prime_square_limit + 1, 2):
31+
if p not in primes:
32+
continue
33+
primes.difference_update(set(range(p * p, prime_square_limit + 1, p)))
34+
35+
for prime1 in primes:
36+
square = prime1 * prime1
37+
for prime2 in primes:
38+
cube = prime2 * prime2 * prime2
39+
if square + cube >= limit - 16:
40+
break
41+
for prime3 in primes:
42+
tetr = prime3 * prime3 * prime3 * prime3
43+
total = square + cube + tetr
44+
if total >= limit:
45+
break
46+
ret.add(total)
47+
48+
return len(ret)
49+
50+
51+
if __name__ == "__main__":
52+
print(f"{solution() = }")

0 commit comments

Comments
 (0)