Advertisement
Yanislav29

Untitled

Dec 26th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. bool isPrime(int n)
  2. {
  3. // Corner cases
  4. if (n <= 1) return false;
  5. if (n <= 3) return true;
  6.  
  7. // This is checked so that we can skip
  8. // middle five numbers in below loop
  9. if (n % 2 == 0 || n % 3 == 0) return false;
  10.  
  11. for (int i = 5; i*i <= n; i = i + 6)
  12. if (n%i == 0 || n % (i + 2) == 0)
  13. return false;
  14.  
  15. return true;
  16. }
  17.  
  18. /* Iterative Function to calculate (x^n)%p in
  19. O(logy) */
  20. int power(int x, unsigned int y, int p)
  21. {
  22. int res = 1; // Initialize result
  23.  
  24. x = x % p; // Update x if it is more than or
  25. // equal to p
  26.  
  27. while (y > 0)
  28. {
  29. // If y is odd, multiply x with result
  30. if (y & 1)
  31. res = (res*x) % p;
  32.  
  33. // y must be even now
  34. y = y >> 1; // y = y/2
  35. x = (x*x) % p;
  36. }
  37. return res;
  38. }
  39.  
  40. // Utility function to store prime factors of a number
  41. void findPrimefactors(unordered_set<int> &s, int n)
  42. {
  43. // Print the number of 2s that divide n
  44. while (n % 2 == 0)
  45. {
  46. s.insert(2);
  47. n = n / 2;
  48. }
  49.  
  50. // n must be odd at this point. So we can skip
  51. // one element (Note i = i +2)
  52. for (int i = 3; i <= sqrt(n); i = i + 2)
  53. {
  54. // While i divides n, print i and divide n
  55. while (n%i == 0)
  56. {
  57. s.insert(i);
  58. n = n / i;
  59. }
  60. }
  61.  
  62. // This condition is to handle the case when
  63. // n is a prime number greater than 2
  64. if (n > 2)
  65. s.insert(n);
  66. }
  67.  
  68. // Function to find smallest primitive root of n
  69. int findPrimitive(int n)
  70. {
  71. unordered_set<int> s;
  72.  
  73. // Check if n is prime or not
  74. if (isPrime(n) == false)
  75. return false;
  76.  
  77.  
  78. int phi = n - 1;
  79.  
  80. // Find prime factors of phi and store in a set
  81. findPrimefactors(s, phi);
  82.  
  83.  
  84. for (int r = 2; r <= phi; r++)
  85. {
  86.  
  87. bool flag = false;
  88. for (auto it = s.begin(); it != s.end(); it++)
  89. {
  90.  
  91. // Check if r^((phi)/primefactors) mod n
  92. // is 1 or not
  93. if (power(r, phi / (*it), n) == 1)
  94. {
  95. flag = true;
  96. break;
  97. }
  98.  
  99. }
  100.  
  101. // If there was no power with value 1.
  102. if (flag == false)
  103. return r;
  104. }
  105.  
  106. // If no primitive root found
  107. return false;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement