Project Euler Homework

007.cpp

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