【发布时间】:2015-12-15 05:10:18
【问题描述】:
我目前正在处理如下所述的任务。我的问题是,为什么我的代码只将质数重复为 2 而不是其余数字。如果有人可以帮助我了解逻辑,我将不胜感激,这样我就可以尝试解决解决方案,而不是直接发布答案。向所有人致敬:)
编写一个使用两个嵌套 for 循环和模数的程序 运算符 (%) 检测并打印从 1 到 10,000 的素数。 (素数是不能被整除的自然数 除了他们自己和一个以外的任何其他数字)。显示所有 找到素数。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> n; // will store our values from 1-10000
for (int i= 0; i < 10000; i++) { // vector loading
n.push_back(i);
n[i]= n[i] + 1;
for (int j= 1; j < 10000 ; j++ ) { // Error is here?
if (n[j] % j == 0) { // supposed to go through all the numbers
// and flag the prime numbers
cout<<n[i] <<" is a prime";
i++;
break;
}
}
}
return 0;
}
【问题讨论】:
-
考虑使用
iterator -
这段代码有几个问题。您是否尝试过添加一些诊断
cout语句并迭代到 10 条?