打印第1000个素数

时间:2015-02-27 11:32:23

标签: c++

#include <iostream>

using namespace std;

int main(){

    int ctr = 0;
    int count = 1; //Counts the nth prime number
    int num = 3;
    int div = 2;  //Potential factors of the number

    while(count <= 1000){
        while(div < num){  
            if(num%div == 0){ 
            ctr += 1; //If ctr is equal to 0, then num is prime
            }
            div += 1;
        }
        if(ctr == 0){ //If num is prime, count increases by 1
            count += 1;
        }
        num += 1;
    }   
    cout << num;
}

这是我输出第1000个素数的代码。但是,我的程序肯定有问题,因为它没有输出7919,这是第1000个素数。

2 个答案:

答案 0 :(得分:0)

将这样的代码重构为具有明确定义和可测试行为的函数通常会有所帮助。例如,代码的内部部分是&#39; isPrime&#39;函数,如果你这样定义:

bool isPrime(int n) {
  int div = 2;  //Potential factors of the number
  while (div < n) {
    if (n % div == 0) {
      return false;
    }
    ++div;
  }
  return div == n;
}

通过单元测试很容易测试,或者只是手动检查isPrime()是否正常。

这使得其余代码更容易编写(更重要的是,读取):

  int primeCount = 0;
  int n = 1;
  while (primeCount < 1000) {
    if (isPrime(n++)) {
      ++primeCount;
    }
  }
  --n;
  std::cout << n << std::endl;

至于为什么你的代码不起作用。你应该调试它。逐行浏览,看看它与您的期望有何偏差。从找到第3个素数开始,而不是第1000个。

你的isPrime部分没有做到它应该做的事情。找出原因并不难,你绝对应该把它作为调试练习,而不是从stackoverflow中得到一个简单的答案。

答案 1 :(得分:0)

#include <stdio.h>




int main(){

int ctr = 0;
int count = 1; //Counts the nth prime number
int num = 3;
int div = 2;  //Potential factors of the number

while(count <= 1000){
    while(div < num){  
        if(num%div == 0){ 
        ctr += 1; //If ctr is equal to 0, then num is prime
        }
        div += 1;
    }
    if(ctr == 0){ //If num is prime, count increases by 1
        count += 1;
    }
    num += 1;
    ctr=0;
    div=2;
}   
printf("%d",num);
}
相关问题