Skip to content

Commit 3d0b194

Browse files
authored
fermatsprime_eastwind.cpp
added prime check by Fermat's algorithm
1 parent e5495d9 commit 3d0b194

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

fermatsprime

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// C++ program to find the smallest twin in given range
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+
/*Recursive function to calculate gcd of 2 numbers*/
25+
int gcd(int a, int b)
26+
{
27+
if(a < b)
28+
return gcd(b, a);
29+
else if(a%b == 0)
30+
return b;
31+
else return gcd(b, a%b);
32+
}
33+
34+
// If n is prime, then always returns true, If n is
35+
// composite than returns false with high probability
36+
// Higher value of k increases probability of correct
37+
// result.
38+
bool isPrime(unsigned int n, int k)
39+
{
40+
// Corner cases
41+
if (n <= 1 || n == 4) return false;
42+
if (n <= 3) return true;
43+
44+
// Try k times
45+
while (k>0)
46+
{
47+
// Pick a random number in [2..n-2]
48+
// Above corner cases make sure that n > 4
49+
int a = 2 + rand()%(n-4);
50+
51+
// Checking if a and n are co-prime
52+
if (gcd(n, a) != 1)
53+
return false;
54+
55+
// Fermat's little theorem
56+
if (power(a, n-1, n) != 1)
57+
return false;
58+
59+
k--;
60+
}
61+
62+
return true;
63+
}
64+
65+
// Driver Program to test above function
66+
int main()
67+
{
68+
int k = 3;
69+
isPrime(11, k)? cout << " true\n": cout << " false\n";
70+
isPrime(15, k)? cout << " true\n": cout << " false\n";
71+
return 0;
72+
}

0 commit comments

Comments
 (0)