为什么%函数在这种情况下不起作用?

时间:2015-01-10 19:43:58

标签: python zero

以下是我一直在努力寻找素数列表的一些代码(请记住,我相当新,我知道这看起来过于复杂)

prime_list=[2,3,5,7,11,13]

prime_list=[2,3,5,7,11,13]

a=1
length=len(prime_list)
last=prime_list[length-1]



true=True
while last < last**2 and a <30:
    last= last+1
    a=a+1
    for number in prime_list:
        if (last)%number == 0:
            true = False
        else:
            pass
    if true == True:
        prime_list.append(last)
    else:
        print("n")
        pass

print(prime_list)

问题的实质是这一点,我得到的只是ns。如同,真正的变量总是假的。由于某种原因,剩余功能不起作用。我真的很感激一些帮助。 (有关具体部分,请查看if last%number == 0:

5 个答案:

答案 0 :(得分:1)

如果你是初学者,我会选择这样的事情:

def isPrime(x): # define a function that will check if 'x' is prime
    if x == 2:
        return True
    i = 2
    while i * i <= x: # this will loop from i = 2 to sqrt(x)
        if x % i == 0: # check if 'i' can divide 'x'
            return False
        i += 1 # this will increase 'i' by 1
    return True

n = 100 # every prime number in 'list' will be below 'n'
list = [] 
for k in range(1, n):
    if isPrime(k): # let see if 'k' is a prime number
        list.append(k) # if 'k' is a prime number add it to the list
print(list) 

对于更有效的算法,我会使用Sieve of Eratosthenes

答案 1 :(得分:1)

last在您的代码中不起作用的原因是它需要在while循环之外定义。这是一个简单的方法。请注意,主要列表和nextNum(我的等同于您的last)是全局定义的。因为它们是在while循环之外定义的,所以它们将从迭代持续到迭代。

primes = []

nextNum = 2
while nextNum < 100 :
    tester = 0 # 0 at the end means nextNum is prime
    for p in primes :
        if nextNum%p == 0 :
            tester += 1
    if tester == 0 :
        primes.append(nextNum)
        print nextNum
    nextNum += 1

答案 2 :(得分:0)

在将设置为False一次后,您永远不会将true(这个变量确实是一个坏名称)重置为True。

在for循环之前将true = True移动到while循环中。

答案 3 :(得分:0)

您正在测试的第一个数字(14)不是主数字,因此标志(名为true的变量)设置为False。到现在为止还挺好。不好的是,自那时起该标志永远不会改变,并且对于所有后续数字仍然是False:没有任何东西可以将其重置为True

在开始迭代潜在的分隔符之前,您需要为您测试的每个数字设置标志变量True。 也就是说,操作符true=True(我讨厌写这个)应该在while内,而不是在它之前。

P.S。运算符%按预期工作。

答案 4 :(得分:0)

martijnn回复的内容可能是初学者的最好例子。如果我们想将他的例子应用到您所创建的特定列表中,就像您在原始代码中所做的那样(只是这样您可以看到与强制100循环的区别,并且您可以了解有关列表和循环的更多信息):

original_list=[2,3,5,6,7,11,13]
prime_list = []

def isPrime(x): # define a function that will check if 'x' is prime
    if x == 2:
        return True
    i = 2
    while i * i <= x: # this will loop from i = 2 to sqrt(x)
        if x % i == 0: # check if 'i' can divide 'x'
            return False
        i += 1 # this will increase 'i' by 1
    return True

for k in original_list:
    if isPrime(k):
        prime_list.append(k)

print prime_list