用户定义的函数在c ++中返回错误的计数

时间:2013-10-31 22:39:49

标签: c++ user-defined-functions

我正在尝试编写程序来计算并显示前50个“chiliads”中的素数。必须有2个用户定义的函数“isPrime”和“primeCount”。似乎“primeCount”正在为每个计数附加4469969。当我将其粘贴到main函数中时,它不会这样做。

int main (){
     long x = 1;
     long y = 1000;
     char reply;   

     cout << "Start   End    Number of Primes" << endl;

    while (y <= 50000)
    {
      cout << x << " " << y << " ";
      cout << primeCount(x, y) << endl;
      x = 1000 + x;
      y = 1000 + y;          
     }

    //exits the program                     
    cout << "Enter q to quit... ";
    cin >> reply;
    return 0;
}// End main function
bool isPrime(long n)
{
 long i = 2;

 if (n == 1)
    return false;
 if (n == 2) 
       return true;
 if (n == 3)
       return true;
 if ((n % 2) == 0)
        return false;
 if ((n % 3) == 0)
        return false;

 while (i < n) 
 {
     if (n % i == 0 )
     {
        return false;
     }
     else 
     {
          i++;
     }      
 }
return true;
}
long primeCount (long x, long y)
{
  long count = 0;
  while (x < y)
  {
      if (isPrime(x) == 1)
      {
         count++;
      }
  x++;  
  }
cout << count;
}

1 个答案:

答案 0 :(得分:1)

您没有从正在打印的“primeCount”中返回值。

我按如下方式清理了代码,并进行了一些优化(我们证明候选者是奇数,所以我们不需要检查偶数除数,我们只检查2的值,当我们已经知道数字时是偶数,每个奇数节省一次额外的测试。)

#include <iostream>

// prototypes for functions we implement after we use them.
long primeCount(long x, long y);
bool isPrime(long n);

int main (){
    long x = 1;
    long y = 1000;

    std::cout << "Start   End    Number of Primes" << std::endl;

    while (y <= 50000)
    {
        std::cout << x << " " << y << " ";
        std::cout << primeCount(x, y) << std::endl;
        x += 1000;
        y += 1000;
    }

    return 0;
}

bool isPrime(long n)
{
    if((n & 1) == 0) // even
       return (n == 2);
    if(n == 1)
        return false;
    for (long i = 3; i < n / 2; i += 2)
    {
        if ((n % i) == 0 )
            return false;
    }
    return true;
}

long primeCount(long x, long y)
{
    long count = 0;
    while (x < y)
    {
        if (isPrime(x))
            count++;
        ++x;
    }

    return count;
}
相关问题