简体   繁体   English

验证输入数字是否为素数

[英]Validate if input number is prime

Trying to write a program that checks if a number is prime.试图编写一个程序来检查一个数字是否是素数。 Wrote the below code, but do not understand why do I have an output of 2 lines:写了下面的代码,但不明白为什么我有2行的output:

num = int(input("Provide number to check if prime: "))
if num <=1:
    print("Invalid choice, try again")
    num = int(input("Provide number to check if prime: "))

for i in range(2,num):
    if num% i ==0:
        print("Number is not prime")
        break
    if num %i !=0:
        print("Number is prime")

My output is:我的 output 是:

Provide number to check if prime: 15
Number is prime
Number is not prime

The sympy.isprime () is a built-in function under the SymPy module and can be utilized for checking of possible prime numbers. sympy.isprime () 是SymPy模块下的内置 function,可用于检查可能的素数。 It is a direct function and returns True if the number to be checked is prime and False if the number is not prime.它是一个直接的 function,如果要检查的数字是素数,则返回 True,如果数字不是素数,则返回 False。

>>> import simpy
  
>>> sympy.isprime(8)

False

>>> sympy.isprime(11)

True

or else define a function like this或者像这样定义一个 function

>>> def isPrime(k):
    
    # 1 is not prime number
    if k==1:
        return False

    # 2, 3 are prime
    if k==2 or k==3: 
        return True

    # even numbers are not prime
    if k%2==0: 
        return False

    # check all numbers till square root of the number , 
    # if the division results in remainder 0
    # (skip 2 since we dont want to divide by even numbers)

    for i in range(3, int(k**0.5)+1, 2):
        if k%i==0:
            return False

    return True

>>> print(isPrime(13))

True

>>> print(isPrime(18))

False

As the first thing, you should remember that 1 isn't a prime number by definition, even if it can't be divided by any other number:首先,你应该记住1根据定义不是质数,即使它不能被任何其他数字整除:

if (num == 1):
    print("The number is NOT prime")
else:
    for i in range(2, num):
        if (num%i == 0): # If the number has a divisor
            print("The number is NOT prime")
            break
    else: # If the for loop ends without reaching any break
        print("The number IS prime")

The else branch of a for loop is reached when the loop ends without reaching any break AND the loop executes at least one time.当循环结束而没有达到任何break并且循环至少执行一次时,就会到达for循环的else分支。

To better understand my answer, I would suggest to read this .为了更好地理解我的答案,我建议阅读内容。


The error with your solution is caused by the loop printing that the number is prime for each time num%i == 0 , so taking num = 6 :您的解决方案的错误是由于循环打印每次num%i == 0时数字都是素数,因此采用num = 6

6%4 != 0 # The number is prime
6%5 != 0 # The number is prime             

As Rajarshi Ghosh suggested, you should know that while programming it's a good idea to use import ed functions to do this simple operations, in order to avoid long operations for such a simple job.正如Rajarshi Ghosh建议的那样,您应该知道,在编程时,使用import ed 函数来执行这个简单的操作是一个好主意,以避免对这样一个简单的工作进行长时间的操作。

If you don't want to use an imported function, I would suggest you to read this article where they explained 6 ways of finding if a number is prime without using functions made by others.如果您不想使用导入的 function,我建议您阅读 这篇文章,他们解释了 6 种方法来查找数字是否为素数,而无需使用其他人制作的函数。

You have issues in output, not only for the case of 15 , but also for cases smaller than 1 .您在 output 中遇到问题,不仅针对15的情况,还针对小于1的情况。 The following code should work.以下代码应该可以工作。 It has two improvements.它有两个改进。

  1. It prints the correct output for 15. The key is to move the else block to align with the for loop.它为 15 打印正确的 output。关键是移动else块以与for循环对齐。
  2. It prints the correct output for any number smaller than 1, which is not prime.它为小于 1 的任何数字(不是素数)打印正确的 output。 The key is to use the while-break method to get user enter right number until it is bigger than 1.关键是使用while-break方法让用户输入正确的数字,直到它大于1。
num = int(input("Provide number to check if prime: "))
while num <=1: #you need to use while loop
    print("Invalid choice, try again")
    num = int(input("Provide number to check if prime: "))
    if num > 1: #only evaluate number is prime or not if it is greater than 1
        for i in range(2,num):
            if num% i ==0:
                print("Number is not prime")
                break
        else: #to move the `else` block to align with the `for` loop.
            print("Number is prime")
        break #add a break here

Output: Output:

在此处输入图像描述

What is a while loop?什么是while循环? A while loop tests the input condition. while 循环测试输入条件。 Every time the loop finishes, the condition is reevaluated (only evaluate number is prime or not if it is greater than 1).每次循环完成时,都会重新评估条件(仅评估数字是否为素数,如果它大于 1)。 As long as the the number entered is <=1 , the loop keeps executing (keep asking users for input).只要输入的数字<=1 ,循环就会继续执行(不断询问用户输入)。

If you want to just check whether a number is prime or not just do the following:如果您只想检查一个数字是否为素数,只需执行以下操作:

num = int(input("Provide number to check if prime: "))

flagNotPrime = False

if num > 1:
    for i in range(2, num):
        if (num % i) == 0:
            flagNotPrime = True
            break

if flagNotPrime:
    print("Number is not prime")

else:
    print("Number is prime")

Firstly, numbers that are <= 1 are not prime numbers.首先, <= 1的数字不是素数。 Therefore, the above code only proceeds if the num is greater than 1.因此,上面的代码只有在num大于 1 时才会继续。

Secondly, the code checks if num is exactly divisible by any number from 2 to num - 1 .其次,代码检查num是否可以被从 2 到num - 1的任何数字整除。 If there is a factor in that range, the number is not prime, so the flag is set to True and the loop is broken using break .如果该范围内有一个因子,则该数字不是素数,因此该标志设置为True并使用break循环。

Lastly, outside the loop, if the flag is True then num is not prime.最后,在循环之外,如果标志为True ,则num不是素数。

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

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