c++ - Finding a prime numbers between 1 - 239 using embedded loop -


i unable figure out how find of prime numbers between 1 , 239 using embedded loop. here code have far know on right track not know go here not returning right output

#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;  } 

you're close. here's working code, if assignment, try work out yourself, , peek @ answer if you're stuck.

      #include <iostream>       using namespace std;        bool isprime(int n){         //first check if n equals 2 or n divisible 2         if (n == 2) return 1;         if (n%2 == 0) return 0;         //start @ 3, check odds, , stop @ square root of n         (int = 3; * <= n; i+=2){          if (n%i == 0)            return 0;         }         return 1;       }        int main()       {         //2 prime number         cout << 2 << " ";         //now rest odds         (int = 3; <= 239; i+=2){           if (isprime(i)){            //print if prime number            cout << << " ";           }         }          cout << endl;                            } 

output:

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

ultra-simplified:

  #include <iostream>   using namespace std;    int main()   {     cout << 2 << " ";      int prime = 1;     (int = 3; <= 239; i+=2){       (int j = 3; j * j <= i; j+=2){          if (i%j == 0){            prime = 0;            break;          }       }        if (prime == 1){         cout << << " ";       }       prime = 1;      }     cout << endl;                        } 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -