【发布时间】:2017-10-12 06:09:03
【问题描述】:
我编写了一个可以找到素数的程序。
from time import sleep
soNotPrimes = []
n = input("Start finding primes at: ")
n = int(n)
k = 2
found_factors = 0
nSQRT = n**0.5
while True:
kinn = n/k
if found_factors == 1:
print("Okay, look man, I totally found a non-prime number. It's", n)
n += 1
k = 2
found_factors = 0
nSQRT = n**0.5
continue
if (k > nSQRT) and found_factors == 0:
print("Oh yeah man, I found a prime!", n)
n += 1
k = 2
found_factors = 0
nSQRT = n**0.5
continue
if kinn.is_integer():
found_factors += 1
k += 1
但是,这不起作用,因为如果数字足够高,Python 就会开始将它们解释为例如 525.31e+10。这将始终等于 5253100000000,它不是素数,因为它是偶数。有没有办法让 Python 从字面上解释这些数字?
【问题讨论】:
-
不,如果这些数字是整数,Python 将在内存中有它们正确的整数表示;您可能只是在查看输出,即 print 给出的表示。
-
另外,您将整数转换为浮点数。例如,您有一个像
n/k这样的部门。改用整数除法n//k(假设那是你想要的)。与使用.is_integer()测试浮点数相比,使用不同的算法来测试可分性。例如,请改用模%运算符。
标签: python python-3.x primes largenumber