I want it to list prime numbers from 1 to 100 like this:

1. 1
2. 2
3. 3
4. 5
5. 7

etc.

#include <iostream>

using namespace std;

int main(){
    
    int num = 1;
    double number = 1;
    double div = 1;
    bool prime = true;
    int top = 100;
    
    
    while (number <= top){          
          while (div < number){                
                if (number / div == int(number / div)){                               
                               div++;                            
                }                
                else {                     
                      prime = false;     
                }
          }
          if (prime == true){                              
                              cout << num << ".        " << number << "\n";
                              num+=1;
          }
          number+=1;
          div=0;
     }
     system("pause");
}

Please help. If there is some random code in there that makes no sense why its there, I probably put it there because I was trying anything to get it to work :P

You can use the operator % (modulo) intsead of / in:

if (number / div == int(number / div)){ ...

so the code would look like this:

if (number % div == 0){ ...
number % div

is the residue of dividing "number" by "div".

I think you are a missing a

prime=true;

somewhere.

Had another go, I REALLY can't see why this doesn't work. All I get is:

2
3

with this code:

#include <iostream>

using namespace std;

int main(){
    
    int number = 2;
    int divider = 2;
    int top = 100;
    bool prime = true;
    bool x = false;
    
    while(number < top){
                 while(divider < number ){
                               if(x == false){
                                        if(number % divider == 0){
                                             prime = false;
                                             x = true;
                                        }
                               }
                 divider += 1;
                 }
                 if(prime == true){
                                   cout << number << "\n";
                 }
                 if(number < top){
                              number += 1;
                 }
                 divider = 2;
    }
    system("pause");
}

with that code you're only reading consecutive prime numbers.

What?

Also, how to fix it?

Just a hint, you only need to check for odd numbers once you're past 2. also the upper limit you have to check is the square root of number because any number above you checked already with its lower part.

This article has been dead for over six months. Start a new discussion instead.