Skip to main content
 首页 » 编程设计

Python 程序因输入大于 3 位数字而失败

2025年05月04日15zlslch

我在做Project Euler's problem 35我的代码失败了,最大值超过 999,但在此之前工作正常。

“计数”在 22 处停止,不计算任何超过 999 的质数。

import itertools 
import time 
 
def isPrime(n): 
    if n % 2 == 0: 
        return n == 2 
    d = 3 
    while d * d <= n: 
        if n % d == 0: 
            return False 
        d += 2 
    return True 
 
t=time.time() 
count=0 
Range=1000000 
for a in range(2,Range):    
    if isPrime(a): 
        alist=[] 
        perms=[] 
        for n in str(a): 
            alist.append(n) 
        for n in itertools.permutations(alist): 
            num=int("".join(n)) 
            perms.append(num) 
        if all(isPrime(l) for l in perms): 
            count+=1 
 
print("there are ", count, " circular primes") 
print("time=",time.time()-t,"s") 

谁能弄清楚为什么会这样?

请您参考如下方法:

前四位循环质数是(我认为)1193。最简单的故障排除方法就是查看该数字发生了什么。问题是 itertools.permutations 生成所有 排列,而不是循环旋转。 1193的循环旋转是

[1193, 3119, 9311, 1931] 

您的代码正在生成一个更大的列表:

[1931, 1913, 1391, 1319, 1193, 1139, 9131, 9113, 9311, 9311, 9113, 9131, 3191, 3119, 3911, 3911, 3119, 3191, 1193, 1139, 1913, 1931, 1319, 1391]  

例如,1391 不是素数。