Taraxacum

isPrime

Nov 15th, 2018 (edited)
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <cmath>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. bool isPrime(const int num) {
  7.     if (num < 2) {
  8.         return false;
  9.     } else if (num < 4) {
  10.         return true;
  11.     } else if (num % 2 == 0) {
  12.         return false;
  13.     }
  14.  
  15.     int sup = sqrt(num) + 1;
  16.     for (int i = 3; i < sup; i += 2) {
  17.         if (num % i == 0) {
  18.             return false;
  19.         }
  20.     }
  21.  
  22.     return true;
  23. }
  24.  
  25. bool Eratosthenes(const int num) {
  26.     if (num < 2) {
  27.         return false;
  28.     } else if (num < 4) {
  29.         return true;
  30.     } else if (num % 2 == 0) {
  31.         return false;
  32.     }
  33.  
  34.     bool *composite = new bool[num + 1]{false};
  35.  
  36.     for (int delta = 3; delta < num; delta += 2) {
  37.         if (!composite[delta]) {
  38.             const int step = 2 * delta;
  39.             for (int n = 3 * delta; n <= num; n += step) {
  40.                 composite[n] = true;
  41.             }
  42.  
  43.             if (composite[num]) {
  44.                 break;
  45.             }
  46.         }
  47.     }
  48.  
  49.     bool result = !composite[num];
  50.     delete[] composite;
  51.     return result;
  52. }
  53.  
  54. int main() {
  55.     for (int i = 1; i <= 100; i++) {
  56.         cout << i << std::boolalpha << "\t" << isPrime(i) << "\t"
  57.              << Eratosthenes(i) << endl;
  58.     }
  59. }
  60.  
Add Comment
Please, Sign In to add comment