繁体   English   中英

用于查找素数的 Python while 循环

[英]Python while loop for finding prime numbers

作为 Python 的第一个练习,我正在尝试编写一个使用循环查找素数的程序。 一切都适用于 for 循环,所以我尝试使用 while 循环。 这有效,但程序返回了一些不正确的数字。

import math
# looking for all primes below this number
max_num = int(input("max number?: "))

primes = [2]  # start with 2
test_num = 3  # which means testing starts with 3

while test_num < max_num:
    i = 0
    # It's only necessary to check with the primes smaller than the square
    # root of the test_num
    while primes[i] < math.sqrt(test_num):
        # using modulo to figure out if test_num is prime or not
        if (test_num % primes[i]) == 0:
            test_num += 1
            break
        else:
            i += 1
    else:
        primes.append(test_num)
        test_num += 1

print(primes)

所以奇怪的是,对于max_num=100它返回:

[2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 25, 29, 31, 37, 41, 43, 47, 49, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

这是正确的,除了 9、25 和 49,我不明白为什么。

您需要达到并包括平方根。 否则您的算法将错过素数方块族(9、25 和 49 是素数方块)。

快速修复是将<替换为<=作为停止条件。

但是考虑将停止条件更改为

primes[i] * primes[i] <= test_num

通过此测试,您不会进出浮点数。

如果您想为每次迭代找到下一个素数,这可能是一个更好的函数,因为它绕过了提供输入的过程。

import math
def primes():
    (h,n) = (2,1)
    k = 2
    while True:
        if any(k % i == 0 for i in range(2,k))==False: # h is composite number, so continue iteration
            (h,n) = (k,n+1) # After the for loop we can find out the next prime number
            k += 1
        else:
            k += 1 # Remember to continue the loop, if not then next function may return the same number
            continue        
        yield h
x = prime()

然后您可以使用以下内容进行迭代:

next(x)

要么

[next(x) for _ in range(20)]

这给出了输出

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]

希望这是一个适合初学者编写素数while循环的优美函数。

for i in range(2,51): for j in range(2,i): if (i%j)==0: break else: print(i," 是质数")

试试这个:

inp = int(input("Enter the number: "))
isDiv = False
i = 2
while i < inp:
if inp%i ==0:
    isDiv = True
    print(f"{inp} is divisible by {i}.")
i+=1   
if isDiv:
    print(f"Hence {inp} is not a prime number.")
else:
    print(f"{inp} is a prime number.")

暂无
暂无

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

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