首页 > 解决方案 > Python - 我提取素数的查询不起作用

问题描述

我正在参加关于 Udemy 的课程,其中一个练习是从一系列数字中返回所有素数(例如 100 之前的所有素数)

这是老师提出的疑问

def count_primes2(num):
    
    #Check for 1 or 0
    if num < 2:
        return 0
    ######################
    #2 or greater
    #Store our prime numbers
    primes = [2] #I start my list with 2 that is a prime number
    #Counter going up to the input num
    x = 3 #I create a variable on which I will continue adding until I reach num
    # x is going through every number up to the input num
    while x <= num:
        #Check if x is prime
        for y in range(3,x,2):  # for y in range from 3 to x in even steps, we only wantto check odd numbers there
            if x%y == 0:
                x += 2 
                break
        else:
            primes.append(x)
            x += 2
    print(primes)
    return len(primes)
count_primes2(100)

但是,我想出了下面那个不起作用的。我的想法是:

给定介于 3 和 num+1 之间的每个数字 i(例如 100 将是 101,因此 100 可以包含在计算中):

我没有在查询中使用任何 while 循环。您能帮我确定为什么我的查询不起作用吗?

def count_prime(num):
    counter=0
    list_prime=[2]
    if num<2:
        return 0
    for i in range(3,num+1):
        for g in range(1,i+1):
            if i%g==0:
                counter+=1
        if counter==2:
            list_prime.append(i)
    
    return list_prime
count_prime(100)   

标签: python

解决方案


感谢 Khelwood的帮助。在工作查询下方:

def count_prime(num):
    counter=0
    list_prime=[2]
    if num<2:
        return 0
    for i in range(3,num+1):
        for g in range(1,i+1):
            if i%g==0:
                counter+=1
        if counter==2:
            list_prime.append(i)
        counter=0
    
    return list_prime
count_prime(100)

推荐阅读