Project Euler Homework

010.cpp

Go to the documentation of this file.
00001 
00009 //application of the sieve of Eratosthenes
00010 
00011 #include <iostream>
00012 #include <iomanip>
00013 
00014 const unsigned largeN = 2e6;    //find all primes from 1 to N.
00015 int count = 0;                  //count the numbers of primes that have found already.
00016 bool primes[largeN + 1];        //index 0 is not needed.
00017 
00018 int
00019 next (int i)                    //move to next prime number
00020 {
00021   int k;
00022   for (k = i + 1; k <= largeN; k++)
00023     if (primes[k] == 1)         //is prime
00024       break;
00025 
00026   return k;                     //if at end, k=largeN+1
00027 }
00028 
00029 double sumP = 0;                //sum of all primes
00030 
00031 int
00032 main ()
00033 {
00034   for (int k = 1; k <= largeN; k++)
00035     primes[k] = 1;              //assume all numbers are prime
00036 
00037   int index = 2;                //starts with 2.
00038   count++;                      //2 is prime
00039   do
00040     {
00041 
00042       sumP += index;            //sum up the prime numbers
00043 
00044       int x = index * 2;
00045       while (x <= largeN)
00046         {
00047           primes[x] = 0;        //exlude all multiples of "number"
00048           x += index;
00049         }
00050 
00051       index = next (index);     //move on to next prime number
00052 
00053       count++;
00054     }
00055   while (index < largeN + 1);   //stop at end
00056   count--;                      //the last one is not within largeN.
00057 
00058   std::cout << "Sum of primes from 1 to " << largeN << " is " << std::
00059     setprecision (20) << sumP << std::endl;
00060   return 0;
00061 }
00062 
 All Classes Files Functions Variables