简体   繁体   English

python中的素数代码是如何工作的?

[英]How the Prime number code in python works?

def is_prime(num):
    for i in range(2,num):
        if (num % i) == 0:
            return False
    return True

def all_primes(num):
    primes = []
    for n in range(2,num+1):
        if is_prime(n) is True:
            primes.append(n)
    return primes

num = int(input("Enter upper limit: "))
primes = all_primes(num)
print(primes)

How does it happens... What understand is if I enter 10 It will be 10%2= 5...the remainder is 0 so it skip to the next one 9%2 = True there is remainder.它是如何发生的... 理解的是,如果我输入 10 它将是 10%2=5...余数为 0 所以它跳到下一个 9%2 = True 有余数。

It moves to the next one 9%3 remainder is 0 so it skips to 8% ...,then 7 .......but what I dont understand is 7 if it's check until 7%7 ==0 then how did it add 7 as Prime number???它移动到下一个 9%3 余数是 0 所以它跳到 8% ...,然后是 7 ......但是我不明白的是 7 如果它检查直到 7%7 ==0 那么如何是不是加了 7 作为素数???

I'm so confused.我很困惑。

Thank you for any comment感谢您的任何评论

but what I dont understand is 7 if it's check until 7%7 ==0但我不明白的是 7 如果它检查到 7%7 ==0

The range function from the following line:来自以下行的range函数

for i in range(2, num):

goes from 2 to num - 1 .2num - 1

So, the range() function doesn't include the last (stop) number in the result.因此, range()函数不包括结果中的最后一个(停止)数字。

You got it wrong.你理解错了。 If you enter 10 , it wouln't check 10%2 and then 9%2 ...如果你输入10 ,它不会检查10%2然后是9%2 ...

It would check 10%2 , then 10%3 , then 10%4 ... ie it would check 10%i , for i ranging from 2 to 9 .它会检查10%2 ,然后是10%3 ,然后是10%4 ... 即它会检查10%i ,因为i范围从29 However, note that execution in is_prime stops as soon as the remainder is 0:但是,请注意,一旦余数为 0, is_prime中的执行is_prime停止:

for i in range(2,num):
        if (num % i) == 0:
            return False

So if num is 10 , only 10%2 would be checked, and since it's 0 , it would immediately return false .因此,如果num10 ,则只会检查10%2 ,并且由于它是0 ,它将立即返回false

If num is 9 , for example, it would check 9%2 .例如,如果num9 ,它将检查9%2 Since the remainder is not 0 , it would move up to checking 9%3 .由于余数不是0 ,它会向上移动到检查9%3 The remainder is 0 there, so it would return false in that case.那里的余数是0 ,所以在这种情况下它会返回false

If num was 7 , it would check 7%2 .如果num7 ,它会检查7%2 The remainder is not 0 so it checks 7%3 , which is also different from 0 , and so on.余数不是0所以它检查7%3 ,这也不同于0 ,依此类推。 The last check performed would be 7%6 , because for i in range(2,num) means that it will iterate with i ranging from 2 to num-1 .最后执行的检查将是7%6 ,因为for i in range(2,num)意味着它将迭代i范围从2num-1 In this case, is_prime(7) would return true because 7%i , with i ranging from 2 to 6 is different than 0 .在这种情况下, is_prime(7)将返回true因为7%i ,其中i范围从26不同于0

A prime number, by definition, is a number that is divisible only by itself and 1.素数,顾名思义,就是一个只能被它自己和1整除的数。

Therefore, your function is_prime gets the number you want to check if it is prime, and try to find any other number that can divide it inside the interval [2, num), this interval is implemented using the function range(2,num) inside the for loop.因此,您的函数is_prime获取您要检查的数是否为素数,并尝试在区间 [2, num) 内找到任何其他可以整除它的数,该区间是使用函数range(2,num)在 for 循环内。

If it finds any case, ie, if the if (num % i) == 0 is satisfied, we know that there is a number which divides it, therefore, by definition it is not a prime number.如果它找到任何情况,即如果满足if (num % i) == 0 ,我们知道有一个数可以整除它,因此,根据定义,它不是素数。 After checking the whole list, if you cannot find a divisor, we can say that the number is prime, ie, the return True on your function.检查整个列表后,如果找不到除数,我们可以说该数字是素数,即在您的函数上return True

Example:
You want to check 9
(1st step) num = 9, i = 2. 9%2 != 0, we continue in the loop with next value of i.
(2nd step) num = 9, i = 3. 9%3 == 0, we return False. As we know, 9 can divide by 3.

Another example:
You want to check 7
num = 7, i = 2 7%2 != 0, so we continue in the loop with the next value of i
num = 7, i = 3 7%3 != 0, so we continue in the loop with the next value of i
num = 7, i = 4 7%4 != 0, so we continue in the loop with the next value of i
num = 7, i = 5 7%5 != 0, so we continue in the loop with the next value of i
num = 7, i = 6 7%6 != 0, so we continue in the loop with the next value of i

The if was never fulfilled, therefore we reach the end of the loop and 
call the next command, which is return True. 

when is_prime is called for number 7 , the loop will run from 2 to 6 only.当为编号7调用is_prime时,循环将仅从2运行到6 Hence 7%7 will never be checked , returning True for such case.因此永远不会检查7%7 ,在这种情况下返回 True 。

Let's consider the two function separately:让我们分别考虑这两个函数:

def is_prime(num):
    for i in range(2,num):
        if (num % i) == 0:
            return False
    return True

This works like this:这像这样工作:

  • let's consider a number num让我们考虑一个数字num
  • get a variable i to assume the value 2得到一个变量i来假设值2
  • evaluate the condition num % i == 0评估条件num % i == 0
  • if the condition is met, then exit from the function and return False如果满足条件,则退出函数并返回False
  • otherwise increment i by 1 and repeat the last two steps until i is equal to num - 1否则将i增加 1 并重复最后两步直到i等于num - 1
  • exit the function and return True退出函数并返回True

So, this never gets to evaluate 7 % 7 : when num is 7 the last value of i is 6 .因此,这永远不会评估7 % 7 :当num7时, i的最后一个值为6


def all_primes(num):
    primes = []
    for n in range(2,num+1):
        if is_prime(n) is True:
            primes.append(n)
    return primes

This gets a number num which is the upper limit of the numbers to consider, then:这会得到一个数字num ,这是要考虑的数字的上限,然后:

  • it creates an empty list named primes它创建一个名为primes的空list
  • it loops n from 2 until num + 1 excluded (or num included)它从2循环n直到排除num + 1 (或包括num
  • if the result of is_prime(n) is True, it appends the number to the list .如果is_prime(n)的结果为 True,则将数字附加到list
  • finally, return the list in primes .最后,返回primeslist

Finally the main body of the script:最后是脚本的主体:

num = int(input("Enter upper limit: "))
primes = all_primes(num)
print(primes)

gets you a string from the keyboard, convert it to int and assign to num , then call all_primes(num) and assign its result to primes and print the list to screen.从键盘获取一个字符串,将其转换为int并分配给num ,然后调用all_primes(num)并将其结果分配给primes并将list打印到屏幕。


So, when you input 10 from the keyboard, it will check the values from 2 to 10 for being prime with is_prime() , and not from 10 and reducing them, as you seems to suggest.因此,当您从键盘输入10时,它会检查从210的值是否为is_prime()素数,而不是从10并减少它们,正如您似乎建议的那样。

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

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