简体   繁体   English

素数的Python函数

[英]Python function for prime number

I want to write a function that returns the number of prime numbers that exist up to and including a given number. 我想编写一个函数,该函数返回存在并包含给定数字的质数的数量。 Function count_primes(100) should return 25 函数count_primes(100)应该返回25

I have written a code which gives 23 instead of 25. The function skips 41 and 71 while counting all other prime numbers in between 1 and 100. Can anyone explain why my code is skipping 41 and 71. My Code is 我编写的代码给出了23而不是25。该函数跳过41和71,同时计算介于1和100之间的所有其他质数。有人可以解释为什么我的代码跳过41和71。我的代码是

import math
def count_primes(num):
    current_number = 4
    number_of_prime = 2
    while current_number <= num:
        is_prime = True
        if current_number%2==0:
            is_prime = False
            current_number += 1
            continue
        else:
            limit = math.ceil(current_number ** 0.5)+1
            for i in range(3, limit, 2):
                if current_number%i==0:
                    is_prime = False
                    current_number += 1
                    continue
        if is_prime == True:
            print(current_number)
            number_of_prime += 1
        current_number += 1
    return number_of_prime
count_primes(100)

I have a written another function which works fine. 我写了另一个功能很好的函数。 I just want to know why this code skips 41 and 71 only. 我只想知道为什么此代码仅跳过41和71。

The problem lies in your inner loop: 问题出在你的内循环中:

for i in range(3, limit, 2):
    if current_number%i==0:
        is_prime = False
        current_number += 1
        continue

The continue statement here only continues the inner loop, not the outer one. 此处的continue语句仅继续内部循环,而不继续外部循环。 That means whenever you test a composite number, it increments current_number but it doesn't go back to testing divisibility by 2. 这意味着,每当您测试一个复合数字时,它都会增加current_number但不会回到2的除数测试。

For example, in the iteration of the outer loop that starts with current_number == 39 , the code finds that it is divisible by 3, so it increments current_number to 40 and continues the inner loop, not the outer one. 例如,在以current_number == 39开始的外循环迭代中,代码发现它可以被3整除,因此它将current_number递增到40,并继续内循环,而不是外循环。 So it tests 40 for divisibility by 5, but not by 3. And since 40 is divisible by 5, it goes on to test 41 for divisibility by 7. Of course 41 is not divisible by 7, but is_prime is still False from back when the code found that 39 is divisible by 3, so 41 doesn't get printed. 因此,它将40除以5,而不是3。并且将40除以5,则继续测试41的7除数。当然,不能将41除以7,但是is_prime从后面返回时仍然为False 。代码发现39可被3整除,因此41不会被打印。

This is a rather peculiar combination of circumstances that only happens to affect 41 and 71 in the range you're testing, because they follow sequences of several reasonably large composite numbers, namely 39,40 and 69,70. 这是一种非常特殊的情况组合,仅会影响您正在测试的范围内的41和71,因为它们遵循几个相当大的复合数字(即39,40和69,70)的序列。

I would suggest going through the exercise of working this out yourself: put print statements where you test for divisibility and you'll see what happens clearly. 我建议您自己动手完成这项工作:将打印语句放在要进行除法测试的位置,然后您会清楚地看到会发生什么。 For example: 例如:

print('testing {} for divisibility by 2: {}'.format(current_number, current_number % 2 == 0))
if current_number%2==0:
    is_prime = False
    ...

and later on 后来

print('testing {} for divisibility by {}: {}'.format(current_number, i, current_number % i == 0))
if current_number%i==0:
    ...

Fixed the code and added comment: 修复了代码并添加了注释:

import math
def count_primes(num):
    current_number = 4
    number_of_prime = 2
    while current_number <= num:
        is_prime = True
        if current_number%2==0:
            is_prime = False
            current_number += 1
            continue
        else:
            limit = math.ceil(current_number ** 0.5)+1
            for i in range(3, limit, 2):
                if current_number%i==0:
                    is_prime = False
                    #current_number += 1 #first increment
                    continue
                    #This continue statement does not skip the next lines (after the for loop) so you increment current_number twice
        if is_prime == True:
            print(current_number)
            number_of_prime += 1
        current_number += 1 #second increment
    return number_of_prime
count_primes(100)

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

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