Python - Prime Finder /计算器错误

时间:2015-01-15 21:44:51

标签: python

好吧,我知道我的代码效率非常低,而且比它长,但我对python很新,只知道一些基本功能。

restart = True
numtocheck = 2 #number to be tested for being a prime
while 0==0: #forever loop
    if restart == True: 
        testnum = 2 #used to test the 'numtocheck' varible
    calculated = numtocheck/testnum
    if (calculated).is_integer():
       numtocheck = numtocheck+1
    else:
        testnum = testnum+1
        if numtocheck == testnum:
            print (numtocheck) #Should be a prime
            numtocheck = numtocheck+1
            restart = True
        else:
            restart = False

输出几乎完全充满素数,但有几个出现,如'35'或'95',每次运行代码时都会出现。我不知道发生了什么,所以任何帮助都会非常感激:)

3 个答案:

答案 0 :(得分:0)

您想要做的事情可能如下:

restart = True
numtocheck = 2 #number to be tested for being a prime
while 0==0: #forever loop
    if restart == True: 
        testnum = 2 #used to test the 'numtocheck' varible
    calculated = numtocheck % testnum    #modulo computation
    if (calculated == 0):
       numtocheck = numtocheck+1
    else:
        testnum = testnum+1
        if numtocheck == testnum:
            print (numtocheck) #Should be a prime
            numtocheck = numtocheck+1
            restart = True
        else:
            restart = False

希望这有帮助...算法可能不完全符合您的预期,但这是另一个主题。

答案 1 :(得分:0)

让我们添加一些调试输出并尝试分析会发生什么。 首先它显然是python 3,因为python 2将不会执行此代码。好。 我将为您的代码添加一些调试输出,如下所示:

restart = True
numtocheck = 2 #number to be tested for being a prime
i = 0
while i<150: #not forever loop now :)
    if restart == True: 
        testnum = 2 #used to test the 'numtocheck' varible
    calculated = numtocheck/testnum
    if (calculated).is_integer():
       numtocheck = numtocheck+1
    else:
        testnum = testnum+1
        if numtocheck == testnum:
            print (numtocheck) #Should be a prime
            numtocheck = numtocheck+1
            restart = True
        else:
            restart = False
    print ('numtocheck %s'%numtocheck)
    print ('testnum %s'%testnum)
    i+=1

好的,这是结果(我把27号作为一个很好的例子):

numtocheck 26
testnum 13
numtocheck 27
testnum 13
numtocheck 27
testnum 14
numtocheck 27

所以我们在这里。您正在检查编号26. 26/12是浮动的,好的,您将testnum增加到13并且26/13是int。欢呼。你去下一个numtocheck - 27.但是忘记清除testnum var并且它仍然是13.所以你从测试27/13开始,然后是27/14,依此类推到27,结果 - 27是一个素数,因为你失去了27/3和27/9。 所以添加

testnum = 2

if (calculated == 0):
       numtocheck = numtocheck+1

一切都会好的。

答案 2 :(得分:0)

我不确定,但似乎你想打印每个素数?由于这只是永远存在,这些数字会变得很大。因此,我添加一个break语句来移动到当前整数被认为是非素数的实例的下一个整数。像这样:

i = 3
while True:
    is_prime = True
    for j in range(2, i):
        if i%j == 0:
            is_prime = False
            break

    if is_prime == True:
        print(i)
    i += 1