简体   繁体   English

欧拉计划第 87 题,主要三元组

[英]Project Euler Problem 87, prime power triplets

The problem goes: How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power?问题是:有多少五千万以下的数可以表示为素数平方、素数立方和素数四次方之和? And here is the link to the problem: https://projecteuler.net/problem=87这是问题的链接: https://projecteuler.net/problem=87

I'm having a problem when trying to get the right answer for higher inputs.我在尝试获得更高输入的正确答案时遇到问题。 My code in python is below.我在 python 中的代码如下。 The function primestill(n) returns a generator of all primes below n and works just fine. function primestill(n)返回低于 n 的所有素数的生成器,并且工作正常。 I would appreciate any help.我将不胜感激任何帮助。

def many2(x):
    counter = 0
    s1 = int(x**(1/4))+1
    for i in primestill(s1):
        s2 = int((x-i**4)**(1/3)) + 1
        for j in primestill(s2):
            s3 = int((x - i**4 - j**3)**(1/2))+1
            for k in primestill(s3):
                if i**4 + j**3 + k**2 < x:
                   counter += 1
    return counter

You should generate a list of primes up to the largest one that will fit under the 50 million mark.您应该生成一个质数列表,直到最大的一个,该列表将适合 5000 万大关。 This would be the largest prime with a square below 50M.这将是正方形小于 50M 的最大素数。

There are only 908 primes up to that largest prime so your loops can just combine these primes.直到最大的素数只有 908 个素数,所以你的循环可以组合这些素数。

Note, however, that there are several combinations of primes that can produce the same sum so you will need to ensure that you count each sum only once (using a set for example).但是请注意,有几种素数组合可以产生相同的总和,因此您需要确保每个总和只计算一次(例如使用集合)。

To optimize the process you can break the nested loops once you reach a prime that would go beyond the maximum (50M):要优化该过程,您可以在达到 go 超出最大值(50M)的素数时打破嵌套循环:

# find eligible primes (Eratosthenes sieve)
N        = 50_000_000
maxPrime = int(N**0.5)
sieve    = [0,0]+[1]*maxPrime
p,np     = 1,2
primes   = []
while np<=maxPrime:
    p,np = np,p+2
    if not sieve[p]: continue
    primes.append(p)
    sieve[p*p::p] = [0]*len(sieve[p*p::p])

# nested loops to count distinct sums made from a**2 + b**3 + c**4
sums = set()
for c in primes:
    for b in primes:
        b3c4 = b**3 + c**4
        if b3c4 >= N: break
        for a in primes:
            s = a*a+b3c4
            if s >= N: break
            sums.add(s)

print(len(sums))    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM