Advertisement
Guest User

LinAGPrime-C++

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