File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed
Competitive Coding/Math/Primality Test/Fermat Method Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ #include < bits/stdc++.h>
3+ using namespace std ;
4+
5+ /* Iterative Function to calculate (a^n)%p in O(logy) */
6+ int power (int a, unsigned int n, int p)
7+ {
8+ int res = 1 ; // Initialize result
9+ a = a % p; // Update 'a' if 'a' >= p
10+
11+ while (n > 0 )
12+ {
13+ // If n is odd, multiply 'a' with result
14+ if (n & 1 )
15+ res = (res*a) % p;
16+
17+ // n must be even now
18+ n = n>>1 ; // n = n/2
19+ a = (a*a) % p;
20+ }
21+ return res;
22+ }
23+
24+ // If n is prime, then always returns true, If n is
25+ // composite than returns false with high probability
26+ // Higher value of k increases probability of correct result.
27+
28+ bool isPrime (unsigned int n, int k)
29+ {
30+ // Corner cases
31+ if (n <= 1 || n == 4 ) return false ;
32+ if (n <= 3 ) return true ;
33+
34+ // Try k times
35+ while (k>0 )
36+ {
37+ // Pick a random number in [2..n-2]
38+ // Above corner cases make sure that n > 4
39+ int a = 2 + rand ()%(n-4 );
40+
41+ // Fermat's little theorem
42+ if (power (a, n-1 , n) != 1 )
43+ return false ;
44+
45+ k--;
46+ }
47+
48+ return true ;
49+ }
50+
51+ // Driver Program
52+ int main ()
53+ {
54+ int k = 3 ;
55+ isPrime (11 , k)? cout << " true\n " : cout << " false\n " ;
56+ isPrime (15 , k)? cout << " true\n " : cout << " false\n " ;
57+ return 0 ;
58+ }
59+
60+
61+ Output:
62+
63+ true
64+ false
You can’t perform that action at this time.
0 commit comments