简体   繁体   English

我想检查一个数字是否是素数,但是下面的代码不起作用,当我输入 65 时它显示,这是一个素数

[英]I want to check if a number is prime or not,but the code below is not working,when i input 65 it shows,this is a prime number

def prime (num) :
    if num == 1 or num == 0 or num == 2:
        return 'This is not a prime number'
    for number in range(2,num):
        if num % number == 0 :
            return 'This is not a prime number'
        else:
            return 'This is a prime number'

This is the code and this is not working result for 65 is prime, why?这是代码,这不是 65 素数的工作结果,为什么?

The problem is you are iterating from 2 till that number.问题是你从 2 迭代到那个数字。 So it goes into the loop, number is 2 , and 65 % 2 != 0 .所以它进入循环,数字是265 % 2 != 0 Hence It returns 'This is a prime number' .因此它返回'This is a prime number' Instead try this:而是试试这个:

def prime(num):
    if num == 1 or num == 0:
        return 'This is not a prime number'
    for number in range(2, num):
        if num % number == 0 :
            return 'This is not a prime number'
    return 'This is a prime number'

What this does is it keeps looping until remainder is 0. If the remainder is never 0, it returns 'This is a prime number'.它的作用是一直循环直到余数为 0。如果余数从不为 0,则返回“这是一个素数”。

PS 2 is a prime number. PS 2 是质数。

there's an elegant algo to solve this problem https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes有一个优雅的算法可以解决这个问题https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

here's my implementation of its caching version这是我对其缓存版本的实现

primes = [1, 2]
def prime(n):
    if n <= 1:
        return 1
    elif n < len(primes):
        return primes[n]
    else:
        p = prime(n-1)+1

        while True:
            for i in range(2, n-1):
                if p%prime(i) == 0:
                    p += 1
                    break
            else:
                primes.append(p)
                return p

for i in range(100):
print(prime(i))

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

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