project-euler/087_prime_power_triples.py

39 lines
947 B
Python

#!/usr/bin/env python3
def main(lim): #exclusive lim
primes = get_primes(bound(lim, 2))
nums = [True] * lim
c = 0
fb = bound(lim, 4)
for frth in primes:
if frth > fb:
break
cb = bound(lim-frth**4, 3)
for cube in primes:
if cube > cb:
break
sb = bound(lim - frth**4 - cube**3, 2)
for sq in primes:
if sq > sb:
break
n = frth**4 + cube**3 + sq**2
c += nums[n]
nums[n] = False
return c
def bound(lim, pw):
return int(lim**(1.0/pw))
def get_primes(lim): #inclusive lim
sieve = [False]*2 + [True] * (lim-1)
p = []
for i in range(2, len(sieve)):
if sieve[i]:
p.append(i)
for j in range(2*i, len(sieve), i):
sieve[j] = False
return p
#print(main(50))
print(main(50*10**6))