我正在创建一个生成素数的程序(是的,我仍然是python的新手)。我的问题是我希望有一个选项来跟踪在此过程中进行了多少计算(使用'yncalc'变量),但如果我使用if语句(围绕'calculate + = 1'行)时间计算时间上升了很多。无论如何,我可以阻止通过命令读取的代码行或没有额外计算时间的东西吗?
这是我的代码
import time
howMany = input("How many prime numbers to solve?\n")
yncalc = input("Keep track of calculations?(slower)\nY or N:")
text = open('PrimeNumbers.txt', 'w')
t = time.clock()
t2 = time.time()
number = 2
primes = []
x1 = 2
x2 = 2
calculations = 0
while True:
if x1 * x2 == number:
number += 1
x1 = 2
x2 = 2
elif x1 < (number / x2):
x1 += 1
elif x1 >= (number / x2) and x2 < number:
x1 = 2
x2 += 1
else:
if (time.clock() - t) > 2:
t = time.clock()
print(primes[-1])
print(len(primes))
if len(primes) == int(howMany):
break
primes.append(number)
number += 1
x1 = 2
x2 = 2
calculations += 1
text.write('%s prime numbers\n' % (len(primes)))
text.write(str(primes))
text.write('\nFinished in %s seconds and took %s calculations' % (str(time.time() - t2)[0:3], calculations))
答案 0 :(得分:0)
如果我正确理解了这个问题,我很困惑为什么不简单地使用if语句。我运行了2000个样本的数字。在我的机器上它只需1秒钟。
calc = yncalc in ("y", "Y", "yes", "Yes")
while True:
# your code
if calc:
calculations += 1
我的结果:2000个样本