Skip to main content
 首页 » 编程设计

python之欧拉挑战12、这段python代码为什么会失败

2025年05月04日12cmt

下面的代码一直告诉我一个错误的数字,我不明白为什么,知道它是蛮力但它应该仍然有效......而且它返回的数字确实有超过 500 个除数,准确地说是 512,帮助会不胜感激

Number = 1 
Count = 2 
Found = False 
while Found == False: 
    Divisors = 0 
    if (Number % 2) != 0: 
        for i in range(1, int(Number**(1/2)), 2): 
            if Number % i == 0: 
                Divisors += 1 
 
    else: 
        for i in range(1, int(Number**(1/2))): 
            if Number % i == 0: 
                Divisors += 1 
 
    if Divisors >= 500: 
        print (Number) 
        Found = True 
 
    else: 
        Number += Count 
        Count += 1 

供引用:Problem 12 from the Euler Challange

请您参考如下方法:

一个整数的约数就是一个整数因式分解中每个纯幂的(1+指数)的乘积。

例如:28 = 2^2 * 7

幂是 2 和 1,所以除数的个数是 (2+1)*(1+1) = 3*2 = 6。简单的

更大的:2047 * 2048/2 = 2^10 * 23 * 89

幂是 10、1 和 1,所以除数的个数是 11*2*2 = 44

更简单:100 = 2^2 * 5^2

幂是 2, 2 所以有 3*3=9 个除数。这同样适用于 36=2^2*3^2。唯一有趣的部分是指数。

因此,使用任何质因数分解(使用筛子,您不需要质性测试)会比尝试每个可能的数字更快、更可靠。

def factorize(i): 
    # returns an array of prime factors 
    whatever 
 
def number_of_divisors(i): 
    n = 1 
    for v in Counter(factorize(i)).values(): 
        n *= v + 1 
    return n