我做了一个简单的小素数检查器在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
这个可能更快:
参考(苏格拉底): https://www.youtube.com/watch?v=2p3kwF04xcA
基本解决方案是:
当然有很多方法可以优化素数程序。下面是一些可以帮助你的链接。你知道吗
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,我发现这仍然对您有用。我将开始评论您的原始代码:
这就给我们留下了这个函数的版本:我怀疑它的速度快得多,但是我认为其中有一些有用的地方。无论如何,你将是法官:-)
相关问题 更多 >
编程相关推荐