简体   繁体   English

确定数字是否为质数

[英]Determining whether a number is prime or not

I know it's been discussed many times; 我知道已经讨论了很多次; I've read it, but somehow I can't get it. 我已经看过了,但是不知怎么回事。 I want to write a program that determines if the entered number is prime or not. 我想编写一个确定输入的数字是否为素数的程序。

One of the implementations I found somewhere on the Internet: 我在Internet上某处找到的一种实现:

from math import *

def main():
    n = abs(input("Enter a number: "))
    i = 2
    msg = 'is a prime number.'
    while i <= sqrt(n):
        if n % i == 0:
            msg = 'is not a prime number.'
        i = i + 1
    print n, msg


main()

A couple of questions here: 这里有几个问题:

  • In the above, what is i , and why does it have a starting value of 2 ? 在上面, i是什么,为什么它的起始值为2
  • What does i = i + 1 do in this program? i = i + 1在此程序中做什么?
  • How does the interpreter know when to print 'is a prime number.' 口译员如何知道何时打印'is a prime number.' even though it is out of the body loop? 即使它超出了身体循环?

A prime number is a number that's only divisible by 1 and itself. 质数是一个只能被1和本身整除的数字。 The method it's using is to try dividing your candidate number n by every other number from 2 up to itself; 它使用的方法是尝试将候选编号n除以其他所有编号(从2到本身); however if any number i is a divisor of your number n then so is n / i and at least one of them is less than or equal to sqrt(n) therefore we need only test up to sqrt(n) inclusive. 但是,如果任何号码i是你数的约数n那么这样是n / i和其中至少有一个小于或等于sqrt(n)因此我们只需要测试多达sqrt(n)包容性。 In practice we need only test the divisors that are actually prime themselves but since we don't have a list of primes to hand we'll test every one. 实际上,我们只需要测试本身就是质数的除数,但是由于我们没有可用的质数列表,因此我们将测试每个素数。

what in the above i is? 在上面的什么i是什么? and why it got a 2 starting value? 为什么它的起始值为2?

i is the potential factor of n we're testing. i是我们正在测试的n的潜在因素。 It starts with 2 because we don't care if 1 divides n (and trivially it will) because the prime definition allows / expects that. 它以2开头,因为我们不在乎1是否除以n (并且微不足道),因为素数定义允许/期望。

what is the i = i + 1 statement, in this concrete example for? 在此具体示例中,i = i + 1语句是什么? Can't see its use in the program. 在程序中看不到它的用途。

It's incrementing the i value at the end of the loop defined by the while i <= sqrt(n) ; 它在while i <= sqrt(n)定义的循环结束时递增i值; it means we advance i to test the next candidate divisor of n . 这意味着我们提前i来测试n的下一个候选除数。

and finally, how python knows when to print 'is a prime number.' 最后,python如何知道何时打印“是素数”。 although it is out of the body loop? 虽然它不在人体循环中?

We initialise msg to "is a prime number" and if we find any divisor then we change it to "is not a prime number" inside the loop. 我们将msg初始化为“是质数”,如果发现除数,则在循环内将其更改为“不是质数”。 If the loop doesn't find a divisor, or if the loop never runs, we'll use the initial value we set which is "is a prime number". 如果循环找不到除数,或者循环从未运行,则将使用我们设置的初始值“是质数”。 Incidentally you could break out of the loop when you find a divisor; 偶然地,当您找到一个除数时,您可能会break循环; there's no point carrying on the test after that. 在那之后进行测试毫无意义。

As another aside you probably want to compute sqrt(n) outside the while and store than in a variable to use in the while - you may be recalculating the square root for every iteration, which is relatively expensive. 作为另一种抛开你可能要计算sqrt(n)的,而在外面和存储比一个变量在使用while -你可能会重新计算平方根每次迭代,这是比较昂贵的。

I've added comments on the sides to explain what each line does: 我在侧面添加了注释,以解释每一行的作用:

from math import * # imports everything from the math module

def main():
    n = abs(input("Enter a number: ")) # gets input from the user
    i = 2 # starts off at 2 because all input is divisble by 1
    msg = 'is a prime number.' # the message is initially set
    while i <= sqrt(n):
        if n % i == 0: # if 'i' divides evenly into n
            msg = 'is not a prime number.' # only set if it isn't a prime
        i = i + 1 # increases 'i' by 1 so it can check every value up to the square-root of 'n' (to see if it divides evenly)
    print n, msg


main()

The program has to go through every value of i (up to the square-root of n ) so that every possible factor is checked. 程序必须遍历i每个值(直到n的平方根),以便检查每个可能的因数。

This is sort of a rough-prime checker, and inefficient for large numbers that aren't prime: If the input was a number like 1234567890 , it will iterate through every number up to the square root of that number, which is 35147 (rounded up). 这有点粗糙,但对于不是质数的数字效率不高:如果输入的数字是1234567890类的数字,它将遍历每个数字直到该数字的平方根35147 (四舍五入)向上)。 Using return statements break the loop, so the first number you check, 2 , it is declared not prime since it is evenly divisible by 2 . 使用return语句中断了循环,因此您检查的第一个数字2声明为不是质数,因为它可以被2整除。 By using return , it will stop the function, and save you 35,146 calculations. 通过使用return ,它将停止该功能,并为您节省35,146个计算。 That isn't a massive number (for computers, at least) but it's still more memory-efficient and takes less time. 这并不是一个大数目(至少对于计算机而言),但是它仍然具有更高的内存效率和更少的时间。

def isPrime(n):
    '''Checks if 'n' is prime.'''
    from math import sqrt
    if n == 0 or n == 1:
        return False
    else:
        for check in range(2, int(sqrt(n))+1):
            if n % check == 0: return False
    return True

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

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