简体   繁体   English

Python:带平方根的素数算法实现

[英]Python: Prime number algortihm implementation with square root

I am trying to solve this problem and despite wrapping my head around it I get stucked over and over and over.我正在尝试解决这个问题,尽管我头昏脑胀,但我一遍又一遍地陷入困境。

I have a list made of one element [2] and given that and knowing that in order to get a prime number $N$ I have to check that it does not have any prime factor smaller or equal than $\\sqrt{N}$, generate all prime numbers between 3 and 100我有一个由一个元素 [2] 组成的列表,并且知道为了得到质数 $N$ 我必须检查它没有任何小于或等于 $\\sqrt{N}$ 的质因数, 生成 3 到 100 之间的所有质数

My code is the following and I will try to explain how I came up with it:我的代码如下,我将尝试解释我是如何想出它的:

prime_numbers = [2]

for k in range(3,100):  # k runs on all numbers to check them
    for i in range (0,len(prime_numbers)): # i is the index of the elements in my list
        if prime_numbers[i] <= sqrt(k):    # first I need to check the sqrt condition
            if k % prime_numbers[i] ==0:     # check that element in list divides k
                k+=1                         # if so k++ and break the cicle
                break
            else:
                i +=1                        # otherwise go to the next elem of the list
        else:                              #if the sqrt condition is not met I have found a prime number    
            value = k
        prime_numbers.append(value)

When I run this code it gets into a loop with no exit, and I cannot individuate where the issue is.当我运行此代码时,它会进入一个没有退出的循环,我无法确定问题出在哪里。 My best guess would be to correct the most indented else condition, but all the attempts I have done have resulted in failure.我最好的猜测是纠正最缩进的 else 条件,但我所做的所有尝试都以失败告终。 Thanks to everyone who is willing to partecipate.感谢所有愿意参与的人。

One way to get there is:到达那里的一种方法是:

from math import sqrt

prime_numbers=[2]

for k in range(3,101):
    prime=True
    for i in range(2, int(sqrt(k))+2):
        if k%i == 0:
            prime=False
            break
    if prime:
            prime_numbers.append(k)

print(prime_numbers)

#Output:
#[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Notes:笔记:

  • It's range(3,101) and not range(3,100) if assuming you want to check all numbers including 100, otherwise your last number checked will be 99.如果假设您要检查包括100在内的所有数字,则它是range(3,101)而不是range(3,100) ,否则您检查的最后一个数字将是 99。
  • Have a boolean variable prime ;有一个布尔变量prime start by assuming the number is prime ( prime=True )首先假设数字是素数( prime=True
  • sqrt(k) returns a float, while your range expects integers; sqrt(k)返回一个浮点数,而您的范围需要整数; as such - int(sqrt(k)) .因此 - int(sqrt(k)) It's +2 to ensure your range 'to' value is never smaller than your 'from' value of 2. +2 以确保您的范围“to”值永远不会小于您的“from”值 2。
  • if k%i == 0 (if you have a divisor) the number is not prime ( prime=False ) and break the for loop to move to the next k if k%i == 0 (如果你有一个除数)这个数字不是素数( prime=False )并break for循环移动到下一个 k
  • This could be my "pythonic" by doing a list comprehension, but it may be easier for you to understand in the current format通过进行列表理解,这可能是我的“pythonic”,但在当前格式中您可能更容易理解

This works:这有效:

prime_numbers = [2]

for prime_candidate in range(3, 100):
    for known_prime in prime_numbers:
        if known_prime <= sqrt(prime_candidate):
            if prime_candidate % known_prime == 0:
                break
    else:
       prime_numbers.append(prime_candidate)

Your problem mainly was, that i += 1 does not prevent prime_numbers.append to append again.您的问题主要是, i += 1不会阻止 prime_numbers.append 再次追加。

The for/else can be substituted by a separate flag to trigger all cases without a break happening earlier. for/else 可以用一个单独的标志代替来触发所有情况,而不会更早发生中断

Thanks to everyone who suggested a solution.感谢所有提出解决方案的人。 Meanwhile I came up with one myself.与此同时,我自己想出了一个。

prime_numbers = [2]


for k in range(3,100):
    for i in range (0,len(prime_numbers)):
        if prime_numbers[i] <= sqrt(k):
            if k % prime_numbers[i] ==0:
                k+=1
                break
            else:
                i +=1
        else:
            value = k
    if(value > max(prime_numbers)):
        prime_numbers.append(value)

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

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