我无法弄清楚如何使用嵌入式循环找到介于1和239之间的所有素数。这是我到目前为止的代码,我知道我在正确的轨道上,但我不知道从哪里开始,因为这不会返回正确的输出
#include <iostream>
using namespace std;
int main()
{
int n, x, y, is_prime;
n = 0;
while (n < 239)
{
n++;
is_prime=1;
x=2;
while (x < n)
{
y = n % x;
if (y == 0)
{is_prime = 0;
x = n;}
else x++;
}
if (is_prime = 1)
cout << n;
cout << endl;
}
system("pause");
return 0;
}
答案 0 :(得分:0)
你很亲密。这里有一些工作代码,但是如果这是一个作业,请尝试自己解决,如果你遇到困难,只需查看答案。
#include <iostream>
using namespace std;
bool isPrime(int n){
//first check if n equals 2 or n is divisible by 2
if (n == 2) return 1;
if (n%2 == 0) return 0;
//start at 3, only check the odds, and stop at square root of n
for (int i = 3; i * i <= n; i+=2){
if (n%i == 0)
return 0;
}
return 1;
}
int main()
{
//2 is the only even prime number
cout << 2 << " ";
//now the rest are odds
for (int i = 3; i <= 239; i+=2){
if (isPrime(i)){
//print i if it is a prime number
cout << i << " ";
}
}
cout << endl;
}
输出:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239
超简化:
#include <iostream>
using namespace std;
int main()
{
cout << 2 << " ";
int prime = 1;
for (int i = 3; i <= 239; i+=2){
for (int j = 3; j * j <= i; j+=2){
if (i%j == 0){
prime = 0;
break;
}
}
if (prime == 1){
cout << i << " ";
}
prime = 1;
}
cout << endl;
}