You have a basic error in your logic.
(您的逻辑中有一个基本错误。)
It's not enough to find out the counter
value is coprime with some previously found prime to determine counter
is prime itself. (这是不够的,找出counter
值是互质与一些以前发现的黄金,以确定counter
是黄金本身。)
You need to test it is coprime with all primes found. (您需要测试它是否与找到的所有素数都互质。)
Suppose counter == 9
and you test it against the first item of your 'prime' numbers, which is 2
.
(假设counter == 9
,然后针对“素数”的第一项2
。)
The result of 9 % 2
is of course 1
, which is not equal zero and your program adds 9
to the array as a prime number. (9 % 2
的结果当然是1
,它不等于零,并且您的程序将9
作为质数加到数组中。)
It happens even earlier for counter == 4
— first you find out it is divisible by 2
and reiterate the loop to find out in the next step 4 % 3 != 0
and add 4
to 'primes'. (对于counter == 4
它甚至更早发生了-首先您发现它可以被2
整除,然后重复循环以在下一步中找到4 % 3 != 0
并将4
加到'primes'。)
As a further result the array overflows (you put more numbers into it than you expected and declared; actually, you put every natural number to it), which means you eventually write past the end of the array, thus triggering an Undefined Behavior.
(进一步的结果是数组溢出(您在其中放入了比预期和声明更多的数字;实际上,您向其添加了每个自然数),这意味着您最终将写入数组的末尾,从而触发了未定义行为。)
That displays also a basic error in the design: you do not check your array_idx
against the array size, which might allow you to handle the error in some civilized manner.
(这也显示了设计中的一个基本错误:您不对照数组大小检查array_idx
,这可能允许您以某种文明的方式处理错误。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…