How to print all prime numbers in c++? -


i'm trying print prime numbers in series, code ended below, instead of printing primes prints random numbers, prime , not :/ why so?

#include <iostream>  using namespace std;  long int x,y=3; int a=3; bool isprime;  int main() {     while(a<=100)     {     for(x=2;x<=y;x++)     {         if(y%x==0 && x!=y)         {             isprime=false;             break;         }         else if(y%x!=0 && x!=y)         {             isprime = true;         }      }     if(isprime==true  && y%x!=0 && x!=y)     {         cout<<a<<" prime number."<<"\n";         isprime=false;     }        a++;       y++;     } } 

this

if(isprime=true && a%x!=0 && a!=y) 

should this

if(isprime==true && a%x!=0 && a!=y) 

that's common mistake. better realise don't need compare bools against true of false, because are true or false. just

if (isprime && a%x!=0 && a!=y) 

the logic looks wrong (and way complicated), try this

    isprime = true;     for(x=2;x<a;x++)     {         if(a%x==0)         {             isprime = false;             break;         }     }     if (isprime)     {         cout<<a<<"\n";     } 

no need y.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -