简体   繁体   English

在python中检查素数

[英]checking prime number in python

i wrote this program to check weather the no.我写了这个程序来检查天气。 is prime or not but it shows the number is prime multiple times.是素数与否,但它多次显示该数字是素数。 how can i solve it我该如何解决

To check weather the number is prime or not.要检查天气,该数字是否为素数。

num = int(input("please enter the number you want to check\n"))

if num > 1:
    for i in range(2, num):
        if (num % i) == 0:
            print("the number is not prime")
            print(str(i) + " times " + str(num//i) + " is "+ str(num))
            break
        else:
            print("the number is prime")
elif(num == 1):
    print("the number is not prime")
else:
    print('enter a positive value')

Your problem is that the else part of your for-loop is wrong.您的问题是 for 循环的else部分是错误的。 You print "the number is prime" every time a division check fails, not just at the end.每次除法检查失败时都打印"the number is prime" ,而不仅仅是在最后。

I added an isPrime boolean that tracks if a single check failed.我添加了一个isPrime布尔值来跟踪单个检查是否失败。 Only if none of them fail, you can print that the number is prime.只有当它们都没有失败时,您才能打印该数字是素数。

num = int(input("please enter the number you want to check\n"))

if num > 1:
    isPrime = True
    for i in range(2, num):
        if (num % i) == 0:
            print("the number is not prime")
            print(str(i) + " times " + str(num//i) + " is "+ str(num))
            isPrime = False
            break
    if isPrime:
        print("the number is prime")
elif(num == 1):
    print("the number is not prime")
else:
    print('enter a positive value')

You can simplify that even more, with a construct of python called for-else (credits to @TheGamer007 ):您可以使用名为for-else的 python 构造进一步简化它(归功于@TheGamer007 ):

num = int(input("please enter the number you want to check\n"))

if num > 1:
    for i in range(2, num):
        if (num % i) == 0:
            print("the number is not prime")
            print(str(i) + " times " + str(num//i) + " is "+ str(num))
            break
    else:
        print("the number is prime")
elif(num == 1):
    print("the number is not prime")
else:
    print('enter a positive value')

It works because Python's for -loops can have an else: following, which only triggers if you don't break out of the loop.它之所以有效,是因为 Python 的for -loops 可以有一个else:以下,它仅在您break循环时才触发。

This might be exactly what you were trying to do.这可能正是您想要做的。 In that case, all you did wrong was your indentation.在那种情况下,您做错的只是缩进。

Also, from an algorithmical point of view, there are much better ways to check.此外,从算法的角度来看,还有更好的检查方法。 A first simple improvement is that you don't need to check range(2,num) , but only range(2, int(math.sqrt(num))+1)第一个简单的改进是你不需要检查range(2,num) ,而只需要检查range(2, int(math.sqrt(num))+1)

Here is my code to check whether a number is prime or not, hope it helps这是我检查一个数字是否为素数的代码,希望对您有所帮助

# Program to Check whether given number is prime

def isPrime(number):
    limit = int(number/2) # limit indicates how many times we need to run the loop
    flag=0                # to keep track whether the number is prime or not
    if number==0 or number==1:
        print(f"The Given Number {number} is Not Prime")
        return
    for i in range(2,limit+1):
        if number%i==0:
            flag=1
            break
    if flag==0:
        print(f"The Given Number {number} is Prime")
    else:
        print(f"The Given Number {number} is Not Prime")

isPrime(1) isPrime(1)

Use a variable, for example flag and initialize it to 0. If the number is not prime,ie i%2==0 set flag to 1 and break, else flag = 0 .使用变量,例如 flag 并将其初始化为 0。如果数字不是素数,即 i%2==0 将 flag 设置为 1 并中断,否则 flag = 0 。

After that come out of the for block, and with the help of if condition display the number is prime or not.之后从 for 块中出来,并借助 if 条件显示数字是否为素数。 That is if flag==0 the number is prime else not.也就是说,如果 flag==0 数字是素数,否则不是。

All you need in order to determine whether a number is prime or not, is to find 1 number that is greater or equal to 2 that divides the number.为了确定一个数是否为素数,您只需要找到一个大于或等于 2 的数来整除该数。

In your loop, you print out a message that says "the number is prime" for each number that does not divide the given number.在您的循环中,您打印出一条消息,为每个不能整除给定数字的数字显示“该数字是质数”。

For example, if you want to check whether the number 9 is prime or not, you will loop all numbers from 2 to 8 and check if they can divide 9. So in your for loop, the number 5 for instance -> 9%5 != 0 -> "the number is prime" message will pop up, which is wrong.例如,如果您想检查数字 9 是否为质数,您将循环从 2 到 8 的所有数字并检查它们是否可以整除 9。因此在您的 for 循环中,例如数字 5 -> 9%5 != 0 -> "the number is prime" 消息会弹出,这是错误的。

The code below shows how you can use a boolean to rise up a flag when the number is NOT prime.下面的代码显示了当数字不是素数时如何使用布尔值来提升标志。

num = int(input("please enter the number you want to check\n"))
isPrime = True
while num < 1:
    int(input("enter a positive value\n"))
if num == 1:
    print("the number is not prime")
    return
for i in range(2, num):
    if (num % i) == 0:
       isPrime = False
       break
print(str(num) + " is prime? " + str(isPrime))

I would suggest the following implementation我建议以下实现

We only need to check/loop up to a square root of the number and not the number itself and is thus faster.我们只需要检查/循环到数字的平方根而不是数字本身,因此速度更快。

The for-else structure gets you rid of the isPrime flag that you otherwise need. for-else 结构使您摆脱了原本需要的isPrime标志。 The way this works is that if the loop finishes normally without breaking (meaning you haven't found what you are looking for) it goes into the else它的工作方式是,如果循环正常完成而没有中断(意味着您还没有找到您要找的else ),它就会进入else

import math

num = int(input("please enter the number you want to check\n"))

if num > 1:
    for i in range(2, int(math.sqrt(num))+1):
        if (num % i) == 0:
            print("the number is not prime")
            print(i, "times", num//i, "is", num)
            break                                                     
    else:        
        print("the number is prime")
else:                                
    print("the number is not prime")

One way to do it:一种方法:

def is_prime(n):
    count = 0
    if x > 1:
        for i in range(1, n + 1):
             if x % i == 0:
                  count += 1
    return count == 2



number = int(input("Insert a number: "))
   if is_prime(number):
      print(str(number) + " is a prime number")
   else:
      print(str(number) + " is not a prime number!")

is_prime(7) # >> Returns True is_prime(7) # >> 返回真

How does it work:它是如何工作的:

A prime number (n) must fullfill the following rules:质数 (n) 必须满足以下规则:

  1. n > 1; n > 1;
  2. n divisible only to 1 and itself( n % 1 == 0, n % n == 0) n 只能被 1 和它自己整除(n % 1 == 0, n % n == 0)

Perform the modulus operation from 1 to n iteratively.迭代执行从 1 到 n 的模数运算。 Increment the variable count every time the result is 0. If the input satisfies the 2nd condition from above then count should be equal 2. If count equals 2 then the number is prime.每次结果为 0 时递增变量计数。如果输入满足上面的第二个条件,则计数应等于 2。如果计数等于 2,则该数字为素数。

Ex:前任:

is_prime(7): 7 % 1 = 0 (count += 1), 7 % 2 = 1, 7 % 3 = 1, 7 % 4 = 3, 7 % 5 = 2, 7 % 6 = 1, 7 % 7 = 0 (count += 1); is_prime(7): 7 % 1 = 0 (count += 1), 7 % 2 = 1, 7 % 3 = 1, 7 % 4 = 3, 7 % 5 = 2, 7 % 6 = 1, 7 % 7 = 0(计数+= 1); >> 7 is prime >> 7 是素数

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

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