英文:
How to fix a triangle of prime numbers
问题
在上面提到的代码中,我尝试打印出一个类似以下的质数三角形:
2
2 3
2 3 5
2 3 5 7
2 3 5 7 11
但是,它打印出了10而不是11。在我尝试创建质数三角形时,我还得到了一些复合数。
当我在第2行中使用了range(15)时,我得到了以下结果:
2
2 3
2 3 5
2 3 5 7
2 3 5 7 10
2 3 5 7 10 11
2 3 5 7 10 11 13
2 3 5 7 10 11 13 17
2 3 5 7 10 11 13 17 19
2 3 5 7 10 11 13 17 19 22
2 3 5 7 10 11 13 17 19 22 23
2 3 5 7 10 11 13 17 19 22 23 25
2 3 5 7 10 11 13 17 19 22 23 25 29
2 3 5 7 10 11 13 17 19 22 23 25 29 31
2 3 5 7 10 11 13 17 19 22 23 25 29 31 34
我无法理解为什么在代码本应只打印质数的情况下,也会出现复合数。
英文:
n=3
for i in range(5):
print(2, end=" ")
for j in range(i):
for k in range(2,n):
if (n%k==0):
n+=1
else:
print (n, end=" ")
n+=1
break
n=3
print()
In the code mentioned above , I'm trying to print out prime numbers in a triangle , like :
2
2 3
2 3 5
2 3 5 7
2 3 5 7 11
But , it prints out 10 instead of 11 .
Please help .
In the prime numbers triangle that I was trying to create , I got some composite numbers too in the way .
Say when I put range(15) in 2nd line , I got :
2
2 3
2 3 5
2 3 5 7
2 3 5 7 10
2 3 5 7 10 11
2 3 5 7 10 11 13
2 3 5 7 10 11 13 17
2 3 5 7 10 11 13 17 19
2 3 5 7 10 11 13 17 19 22
2 3 5 7 10 11 13 17 19 22 23
2 3 5 7 10 11 13 17 19 22 23 25
2 3 5 7 10 11 13 17 19 22 23 25 29
2 3 5 7 10 11 13 17 19 22 23 25 29 31
2 3 5 7 10 11 13 17 19 22 23 25 29 31 34
I am not able to understand that how do composite numbers , too , come in the triangle , when the code was supposed to print only prime numbers there .
答案1
得分: 0
你的代码逻辑有问题。这两行:
if (n%k==0):
n+=1
在检测到n
不是质数后,没有将k
重置为2
。因此,在增加n
后,k
会继续从之前的值开始。此外,这个语句:
else:
print (n, end=" ")
意味着如果检查的第一个k
值不是n
的因子,就会自动假设n
是质数。这是不正确的,因为如果n
是合数,可能会有其他值的k
是它的因子。
可以尝试像这样修改代码:
n=3
for i in range(5):
print(2, end=" ")
for j in range(i):
ok = False
while not ok:
ok = True
for k in range(2,n):
if (n%k==0):
ok = False
break
if not ok:
n += 1
print (n, end=" ")
n += 1
n=3
print()
在这里,ok
跟踪当前的 n
值是否为质数。
英文:
The logic of your code is flawed. These two lines:
if (n%k==0):
n+=1
do not reset k
to 2
after n
has been detected as not being prime. Therefore, after you increment n
, k
continues where it has left off. Furthermore, this statement
else:
print (n, end=" ")
means that n
is automatically assumed as prime
if the first value of k
checked is not a factor of n
. This is incorrect as there may be other values of k
that are factors of n
if n
is composite.
Try something like this instead:
n=3
for i in range(5):
print(2, end=" ")
for j in range(i):
ok = False
while not ok:
ok = True
for k in range(2,n):
if (n%k==0):
ok = False
break
if not ok:
n += 1
print (n, end=" ")
n += 1
n=3
print()
Here, ok
tracks if the current value of n
is prime or not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论