Adding numbers

// how do I add all the "prime" numbers instead of displaying them..

//example... cout << "there are 125 prime numbers";

//im using the number 1000 because I want to find out how many prime numbers it has...

//I don't want to display the numbers i want to know how many...

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <math.h>
#include <stdio.h>



using namespace std;


int main()

{
for (int a=2 ; a < 1000 ; a++)
{
bool prime = true;

for(int c=2 ; c*c <= a ; c++)
{

if(a % c == 0)
{
prime = false;
break;
}


}
if(prime) cout << a << " ";



}

return 0;
}
You would want to do something along the lines of checking to see if it is a prime number first, if it is then have a variable counter

so like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

int count = 0;
for (int a = 2; a < 1000; a++)
{
     bool prime = true;
    
     for (int c = 2; c*c <=a; c++)
     {
           if (a%c == 0)
          {
                 prime = false;
                 break;
           }
      }
     
      if (prime)
     {
          count++
      }
}  //end of for loop
cout << "There are " << count << " prime numbers << endl;
 



This is the basic idea you will want to shoot for. I did not check your logic and finding the prime numbers but this is the basic idea. You just need to add + 1 to some variable each time a prime is found and then display that number after both for loops have done their thang. Yes, I said thang.
Topic archived. No new replies allowed.