简体   繁体   English

如何使用 python 检查素数

[英]How to check for a prime number using python

I wrote the code below to check for prime numbers but when I run the code both the if and else statements execute the same output.我编写了下面的代码来检查素数,但是当我运行代码时, ifelse语句都执行相同的 output。

n = int(input("enter a number\n"))
for i in range(2, n):
    if n % i == 0:
        print(f"{n} is not prime")
    else:
        print(f"{n} is prime")

Sympy.isprime is probably the most efficient way unless you want to check various numbers. Sympy.isprime可能是最有效的方法,除非您想检查各种数字。 In that case, it's better to use the Sieve of Eratosthenes .在这种情况下,最好使用埃拉托色尼筛

If you do not want to use modules or semi-complicated algorithms, the following plain code works perfectly if you need to check just a few numbers smaller than 10**6.如果您不想使用模块或半复杂的算法,如果您只需要检查几个小于 10**6 的数字,则以下纯代码可以完美运行。

def isprime(num):
    for n in range(2,int(num**0.5)+1): 
        if num%n==0:
            return False
    return True

The issue you have is that your loop prints out something on every iteration.您遇到的问题是您的循环在每次迭代时都会打印出一些东西 You can't do that if you only want to print that n is prime when you're sure it is.如果您只想在确定n是素数时打印它,则不能这样做。 You can only be sure of that when your whole loop completes.只有当整个循环完成时,您才能确定这一点。

This is easiest in a function, where you can return whenever you have a firm answer:这在 function 中是最简单的,只要您有明确的答案,您就可以return

def prime_check(n):
    for i in range(2, n):
        if n % i == 0:
            return False
    return True             # this only runs after the whole loop ends


n = int(input("enter a number\n"))
if prime_check(n):
    print(f"{n} is prime")
else:
    print(f"{n} is not prime")

If you want to keep the check inline, rather than using a function, you can do that too, with some clever use of break and the else clause attached to the loop , rather than the if .如果你想保持检查内联,而不是使用 function,你也可以这样做,巧妙地使用break附加到循环else子句,而不是if Such a clause only runs if the loop exits normally, not if it's exited early by a break statement.这样的子句仅在循环正常退出时运行,而不是在它被break语句提前退出时运行。 This can be a bit confusing, which is why I put it second, after the return version that is a lot more clear.这可能有点令人困惑,这就是为什么我把它放在第二位,在更清晰的return版本之后。

n = int(input("enter a number\n"))
for i in range(2, n):
    if n % i == 0:
        print(f"{n} is not prime")
        break
else:                       # the else is attached to the for loop now, not the if
    print(f"{n} is prime")  # this line is only runs if no break happened in the loop

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

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