查找素数的程序意外停止

AvZ*_*AvZ 0 c++ for-loop numbers

我写了一个非常简单的程序来查找由用户指定的特定范围内的素数.但我遇到了一个问题.当程序达到复合数时,程序只会停止打印出素数.我试着看看为什么它会停止,但我根本无法理解它有什么问题可能因为我是编程的新手.无论如何,这是代码.

#include <iostream>
using namespace std;
int main()
{
    int y;
    int range;
    cout << "Please enter the range. \n";
    cin >> range;
    for (y = 2; y <= range; y++)
    {
        int result;
        for (int x = 1; x < y - 1; x++)
        {
            int prime = y - x;
            if (y%prime != 0)
            {

            }
            else
            {
                result = 0;
            }
        }
        if (result != 0)
        {
            cout << y << " is a prime number. \n";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Abh*_*sal 5

正如Brian Gradin指出的那样,我看到的唯一问题是你应该将结果初始化为非零整数.

int result = 1;
Run Code Online (Sandbox Code Playgroud)

只有在初始化之后才能在for循环后进行有效检查,结果是否已更改为零.

如果没有初始化,任何对此变量值的访问都会导致未定义的行为.

编辑:

为了完整起见,我应该添加其他人的建议,这样做的标准方法是:

for (y = 2; y <= range; y++)
{
  bool isPrime = true;

  // The following loop should be changed to loop through the Sieve of primes
  for (int x = 2; x*x < y ; x++) // You need to loop only till sqrt(y)
  {
    if (y%x == 0) // if you found a factor
    {
      isPrime = false;
      break;
    }
  }
  if ( isPrime )
  {
    cout << y << " is a prime number. \n";
    // and add this to the sieve of primes.
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 一旦做出这种改变,我可以确认原始代码是否有效.+1 (2认同)