Guest User

Untitled

a guest
Jan 21st, 2016
3,171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. typedef long long ll;
  2.  
  3. ll mulmod(ll a, ll b, ll c) {
  4. ll x = 0, y = a % c;
  5. while (b) {
  6. if (b & 1) x = (x + y) % c;
  7. y = (y << 1) % c;
  8. b >>= 1;
  9. }
  10. return x % c;
  11. }
  12.  
  13. ll fastPow(ll x, ll n, ll MOD) {
  14. ll ret = 1;
  15. while (n) {
  16. if (n & 1) ret = mulmod(ret, x, MOD);
  17. x = mulmod(x, x, MOD);
  18. n >>= 1;
  19. }
  20. return ret;
  21. }
  22.  
  23. bool isPrime(ll n) {
  24. ll d = n - 1;
  25. int s = 0;
  26. while (d % 2 == 0) {
  27. s++;
  28. d >>= 1;
  29. }
  30.  
  31. // It's guranteed that these values will work for any number smaller than 3*10**18 (3 and 18 zeros)
  32. int a[9] = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };
  33. for(int i = 0; i < 9; i++) {
  34. bool comp = fastPow(a[i], d, n) != 1;
  35. if(comp) for(int j = 0; j < s; j++) {
  36. ll fp = fastPow(a[i], (1LL << (ll)j)*d, n);
  37. if (fp == n - 1) {
  38. comp = false;
  39. break;
  40. }
  41. }
  42. if(comp) return false;
  43. }
  44. return true;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment