Advertisement
Guest User

Untitled

a guest
Oct 1st, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4.  
  5. #define int64_t __int64
  6.  
  7. std::vector<int64_t> allPrimes;
  8.  
  9. int isPrime(int64_t param)
  10. {
  11.     if (param == 2)
  12.         return 1;
  13.  
  14.     if ((param % 2) == 0)
  15.         return 0;
  16.  
  17.     int64_t limit = (int64_t)sqrt((long double)param);
  18.  
  19.     // start at 2 since already done 2
  20.     // even numbers cant be prime
  21.     for (int i = 3; i <= limit; i += 2)
  22.     {
  23.         if ((param % i) == 0)
  24.             return 0;
  25.     }
  26.  
  27.     return 1;
  28. }
  29.  
  30. int main()
  31. {
  32.     int64_t i;
  33.     int64_t limit = 100000000 >> 1;
  34.  
  35.     // Precalculate all primes
  36.     for (i = 2; i < limit; i++)
  37.     {
  38.         if (isPrime(i))
  39.             allPrimes.push_back(i);
  40.  
  41.         if ((i % 1000000) == 0)
  42.             std::cout << "Done a million" << std::endl;
  43.     }
  44.  
  45.     std::cout << "Primes precalculated" << std::endl;
  46.  
  47.     int64_t goodOnes = 0;
  48.     int64_t max = 100000000;
  49.     int64_t numPrimes = allPrimes.size();
  50.     int64_t j;
  51.  
  52.     // Check primes against each other (order doesnt matter)
  53.     for (i = 0; i < numPrimes; i++)
  54.     {
  55.         for (j = i; j < numPrimes; j++)
  56.         {
  57.             // If the product is less than 10^8 we have found a number
  58.             // with exactly 2 prime factors, else we move forward in the
  59.             // prime vector
  60.             if ((allPrimes[i] * allPrimes[j]) < max)
  61.                 goodOnes++;
  62.             else
  63.                 break;
  64.         }
  65.     }
  66.  
  67.     std::cout << "Primes precalculated, good ones: " << goodOnes << std::endl;
  68.     getchar();
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement