我是python的新手,试图运行这个"检查素数程序"

时间:2017-05-31 10:45:42

标签: python python-3.x

num=int(input("Enter any number : -"))
for i in range(num):
    if(num <= 1):
        print("Please enter a number more than 1")

    elif(num%i ==0):
        print("The number is not a prime number")
        break
    else:
        print("The number is a prime number")
        break

但是当我给出0或小于1的值时,我犯了一个错误。它开始出现错误。

1 个答案:

答案 0 :(得分:3)

有许多有效的方法可以检查数字是否为素数。

此处What is the best algorithm for checking if a number is prime?

然而,针对您的问题,有很多错误:

1)由于Zero Divison Error导致代码失败,因为你的范围从0开始,尝试

for in range(2, num)

因为num%1总是为零

2)if(num <= 1):应该在for循环之外,以避免不必要的循环

以下是脚本的简单修改版本:

num = int(input("Enter any number : "))

def check_prime(num):
    if(num <= 1):
        print("Please enter a number more than 1")
        return

    # check if number is 2 or 3 as they are prime numbers
    if (num == 2 or num == 3):
        print("Number is prime")
        return

    # checking for number divisible by 2, 3 or 5 covers large set of numbers
    if (num % 2 == 0 or num % 3 == 0):
        print("Number is not a prime number")
        return

    # if none of the above case is satisfied then iterate to half of the number
    # as number more than half is never a factorial of the number
    for i in range(7, int(num / 2)):
        if(num % i == 0):
            print("The number is not a prime number")
            return
    print("Number is prime")


check_prime(num)

但是,有一些有效的解决方案。