Advertisement
LinAGKar

LinAGPrime-C++98

Oct 12th, 2015
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4. #include <cstdlib>
  5.  
  6. using namespace std;
  7.  
  8. int main(int argc, char* argv[]) {
  9.     if(argc < 2) {
  10.         cerr << "Must specify max, e.g. \"" << argv[0] << " 10000000\"" << endl;
  11.         return -1;
  12.     } else if(argc > 2) {
  13.         cerr << "Too many arguments" << endl;
  14.         return -1;
  15.     }
  16.  
  17.     const int MAX = atoi(argv[1]); // Programmet hittar all primtal under MAX
  18.     vector<int> primes;
  19.  
  20.     for(int i = 2; i < MAX; i++) {
  21.         bool divisible = false;
  22.         const double ROOT = sqrt(i);
  23.  
  24.         for(int j = 0; j < primes.size(); j++) {
  25.             if(primes.at(j) > ROOT) break;
  26.             if((i % primes.at(j)) == 0) { // Testar om talet är delbart
  27.                 divisible = true;
  28.                 break;
  29.             }
  30.         }
  31.  
  32.         if(not divisible) { // Hittat ett primtal
  33.             primes.push_back(i);
  34.             cout << i << endl;
  35.         }
  36.     }
  37.  
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement