当我运行这段代码时,即使只计算前十个质数(而不是1000),我也会得到一个偏斜/失真的输出--我的is_composite变量所有的标题都是“not prime”,我的test_num给我质数和合数,而我的prime_count也有误。
一些开发人员分享的答案使用了函数和math导入--这是我们尚未涵盖的内容。我并不试图得到最有效的答案;我只是想编写可行的Python代码来理解循环的基础知识。
一些开发人员分享的答案使用了函数和math导入--这是我们尚未涵盖的内容。我并不试图得到最有效的答案;我只是想编写可行的Python代码来理解循环的基础知识。
# test a prime by diving number by previous sequence of number(s) (% == 0). Do this by
# counting up from 1 all the way to 1000.
test_num = 2 #these are the numbers that are being tested for primality
is_composite = 'not prime' # will be counted by prime_count
prime_count = 0 #count the number of primes
while (prime_count<10): #counts number primes and make sures that loop stops after the 1000th prime (here: I am just running it to the tenth for quick testing)
test_num = test_num + 1 # starts with two, tested for primality and counted if so
x = test_num - 1 #denominator for prime equation
while (x>2):
if test_num%(x) == 0:
is_composite = 'not prime'
else:
prime_count = prime_count + 1
x = x - 1
print is_composite
print test_num
print prime_count