我用python做了一个质数检查器。可以优化吗?

2024-10-03 00:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个简单的小素数检查器在python作为我的第一个项目,而学习。如何改进?例如,这是我能做的最紧凑的吗?你知道吗

def isPrime(input):
    check = input - 1
    checkmod = input % check
    for i in range (input):
        checkmod = input % check
        check -=1

        if checkmod != 0 and input > 1 and check <= 1 or input == 2:
            return 'Prime'

        elif checkmod == 0 and check > 1:
            return 'Not prime'

print(isPrime(numberhere)) # where to put in number

Tags: orand项目inforinputreturnif
3条回答

这个可能更快:

import math

def is_prime(n):
    ''' return True if n is a prime number. False otherwise.'''
    # negative numbers, 0, and 1 are not prime
    if n <= 1:
        return False
    # 2 is prime
    if n == 2:
        return True
    # non-2 even numbers are not prime
    if n % 2 == 0:
        return False
    # loop through odd divisors up to its sqrt
    for i in range(3, math.ceil(math.sqrt(n)), 2):
        if n % i == 0:
            return False
    return True

参考(苏格拉底): https://www.youtube.com/watch?v=2p3kwF04xcA

基本解决方案是:

def isprime(num):
    if not (isinstance(num,int)):    #checking number should be integer
        return "Enter a valid number"
    elif (num < 0):    #checking number should be positive
        return "Enter a positive number"
    else:
        for i in range(2,num):    #start the loop from 2 upto number
            if num % i == 0:      #checking prime condition
                return "Number is not Prime"    #if found not prime return here
                break    #and exit from loop
        else:
            return "Number is Prime"     #if found prime return here

print(isprime(7))    #calling the method here

当然有很多方法可以优化素数程序。下面是一些可以帮助你的链接。你知道吗

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

https://en.m.wikipedia.org/wiki/Primality_test

https://web.archive.org/web/20080324064651/http://krenzel.info/?p=83

尊重@Shadow和@Scott的评论,有一些东西可以用不同的方式来写。既然您正在学习python,我发现这仍然对您有用。我将开始评论您的原始代码:

def isPrime(input):
    check = input - 1
    checkmod = input % check    # checkmod is recalculated in the loop: eliminate
    for i in range (input):
        checkmod = input % check
        check -=1

        # The test condition below can be simplified. For example, you
        # test that input>1 or input==2 at every loop, when in fact input
        # never changes after entering the function. I think that those
        # two tests should shortcut at the very beginning. 
        #
        if checkmod != 0 and input > 1 and check <= 1 or input == 2:
            return 'Prime'

        # Not sure if this is an optimization, but the two statements
        # seem quite separate. I would use either "else" or just simply
        # another "if"
        elif checkmod == 0 and check > 1:
            return 'Not prime'

这就给我们留下了这个函数的版本:我怀疑它的速度快得多,但是我认为其中有一些有用的地方。无论如何,你将是法官:-)

def isPrime(input):
    # room here to test input>=1
    if input in [1, 2]:
        return 'Prime'
    # if you work out the sequence of values for check
    # they can be generated via range(). Mindful though
    # that the comparison has to be adjusted against (i-1)
    # which can be simplified by moving -1 to the other side
    # hence comparing against 2
    #
    for i in range(input-1, 0, -1):
        checkmod = input % i
        if checkmod != 0 and i <= 2:
            return 'Prime'
        if checkmod == 0 and i > 2:
            return 'Not prime'

numberhere = 22
print(isPrime(numberhere))  # where to put in number

相关问题 更多 >