查找素数的程序意外停止

A program to find prime numbers stops unexpectedly

本文关键字:意外 程序 查找      更新时间:2023-10-16

我写了一个非常简单的程序来查找用户指定的某个范围内的素数。但是我遇到了一个问题。程序只是在达到合数时停止打印出素数。我试图了解为什么它会停止,但我根本不明白它有什么问题,可能是因为我是编程新手。无论如何,这是代码。

#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";
        }
    }
}

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

int result = 1;

只有在此初始化之后,才能在 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.
  }
}
int main()
{
    int y;
    int range;
    int result;
    int prime;
    cout << "Please enter the range. n";
    cin >> range;
    for (y = 2; y <= range; y++)
    {
       result=1;
        for (int x = 1; x <= y - 1; x++)
        {
             prime = y - x;
            if (y%prime != 0)
            {
            }
            else
            {
                result = 0;
            }
        }
        if (result != 0)
        {
            cout << y << " is a prime number. n";
        }
    }
}

我已经更改了您的 forloops 限制语句..!!

 for (int x = 1; x <= y - 1; x++)

并将您的声明更改为顶部:

int result=0;
    int prime;