Saturday, November 16, 2013

Sum of primes below 5000

What is the sum of all prime numbers below 5000?

Language C++:


#include<iostream>
using namespace std;

class prime {
          private:
                int sumprime;
          public:
                prime() { 
                      sumprime = 2;
                }
                void calc_sumprime() { 
                      int i,counter = 0;
                      int num = 3;
                      while (num <= 5000) { 
                              for(i = 2 ; i < num ; i++) { 
                                      if((num % i) == 0) {
                                              counter++;
                                              break;
                                       }
                               }
                               if(counter == 0) {
                                      sumprime += num;
                               }
                               counter = 0;
                               num++;    
                       }
                       cout<<"sum = "<<sumprime<<endl;
                 }
};

int main() {
        prime obj;
        obj.calc_sumprime();
        return(0);
}

Output:
1548136

By +Dixit Singla 
Post a Comment