[英]A prime number checker that fails
It seems like a normal code and works well, but for whatever reasons when I try entering this number = 18765411123451, computer seems to freeze, any clue? 似乎是正常的代码,并且运行良好,但是由于任何原因,当我尝试输入此号码= 18765411123451时,计算机似乎死机了,有什么线索吗?
num = 18765411123451
if num > 1:
for i in range(2,num):
if num % i == 0:
print(num,"is not a prime number")
print("Because", i,"x",num//i, "=" ,num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
I've tried many other numbers and the code works as it should except that number. 我尝试了许多其他数字,除了该数字外,代码也可以正常工作。 What happened here?
这里发生了什么?
it freezes because your number just too high. 它冻结,因为您的电话号码太高了。
The reason is for i in range(2,num):
with num = 18765411123451
with is 100 trillion... 原因是
for i in range(2,num):
num = 18765411123451
with是100万亿...
Plus the fact that python 2 will try to allocate that memory just to create the list to iterate on it (in that case use xrange
) 加上python 2将尝试分配该内存只是为了创建要在其上进行迭代的列表(在这种情况下,请使用
xrange
)
Good news: you don't have to check until the number itself, just check until square root (included): 好消息:您不必检查数字本身,只需检查直到平方根(包括)即可:
for i in range(2,int(num**0.5)+1):
that's more reasonable (less that 5 million iterations) and will provide the same result. 这样比较合理(少于500万次迭代),并且将提供相同的结果。
Past the square root of a number, if you haven't found divisors, you won't find any afterwards (if q
is a divisor of num
, then p*q == num
so either p
or q
has to be lower or equal than square root of num
超过数字的平方根后,如果尚未找到除数,则以后将找不到任何值(如果
q
是num
的除数,则p*q == num
因此p
或q
必须小于或等于比num
平方根
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.