Advertisement
joric

megaprime-numbers.cpp

Feb 28th, 2017
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. long mulmod(long a, long b, long c){
  6.     long x = 0, y = a%c;
  7.     while(b){
  8.         if(b&1){
  9.             x += y;
  10.             if(x >= c) x -= c;
  11.         }
  12.         y = y * 2;
  13.         if(y >= c) y -= c;
  14.         b >>= 1;
  15.     }
  16.     return x;
  17. }
  18.  
  19. long BigMod(long a, long b, long mod){
  20.     if(b == 0) return 1;
  21.     long x = BigMod(a, b >> 1, mod);
  22.     x = mulmod(x,x,mod);
  23.     if(b&1)
  24.         x = mulmod(x,a,mod);
  25.     return x;
  26. }
  27.  
  28. int miller_rabin(long n, int itr = 3){
  29.     if(n < 2) return 0;
  30.     else if(n == 2) return 1;
  31.     if(n%2 == 0) return 0;
  32.     long d = n - 1;
  33.     while(d%2 == 0)
  34.         d /= 2;
  35.     while(itr--){
  36.         long rnd = rand() % (n - 2) + 2;
  37.         long temp = d;
  38.         long x = BigMod(rnd, temp, n);
  39.         while(temp != (n - 1) && x!=1 && x!=(n-1) )
  40.         {
  41.             temp *= 2;
  42.             x = mulmod(x,x,n);
  43.         }
  44.         if(x != (n - 1) && temp%2 == 0)
  45.             return false;
  46.     }
  47.     return true;
  48. }
  49.  
  50. long next(long x) {
  51.     if (x == 0) return 0;
  52.     long d = x / 10;
  53.     long d1 = next(d + (x % 10 > 7 ? 1 : 0));
  54.     if (d != d1) return 10 * d1 + 2;
  55.     return d1 * 10 + (x % 10 <= 2 ? 2 : x % 10 <= 3 ? 3 : x % 10 <= 5 ? 5 : 7);
  56. }
  57.  
  58. int main(){
  59.     long first;
  60.     long last;
  61.     cin >> first >> last;
  62.     int count = 0;
  63.     for (long i = next(first); i<=last; i=next(i+1)) if (miller_rabin(i)) count++;
  64.     cout << count;
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement