使用嵌入循环查找1-239之间的素数

Finding a prime numbers between 1 - 239 using embedded loop

本文关键字:之间 1-239 查找 循环      更新时间:2023-10-16

我不知道如何使用嵌入式循环找到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;
}

你很接近。这里有一些工作代码,但如果这是一项任务,试着自己解决,如果你陷入困境,就看看答案。

      #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 31 37 41 47 53 59 61 67 71 73 83 89 97101 103 107 109 113 127 131 137 139 149 151 157 163 173 179 181191 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;                     
  }