From 87b9f4bc529aab4e8f3bb05638c7d49c8e5a4d50 Mon Sep 17 00:00:00 2001 From: npav5057 Date: Mon, 2 Oct 2023 11:48:29 +0530 Subject: [PATCH] Added Primality test cpp files --- C++/ISPRIME.cpp | 35 ++++++++++++++++++++++++ C++/MillerRabin.cpp | 65 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 C++/ISPRIME.cpp create mode 100644 C++/MillerRabin.cpp diff --git a/C++/ISPRIME.cpp b/C++/ISPRIME.cpp new file mode 100644 index 0000000..c11c936 --- /dev/null +++ b/C++/ISPRIME.cpp @@ -0,0 +1,35 @@ +/* + + Simple algorthiam to check Primality of a 32 bit int + Time complaxity : O(sqrt(n/3)) +*/ + +#include +#include + +using namespace std; +bool isPrime(int num) +{ + if(num < 4) return n>1; + + if(!(num&1) or num%3==0 ) return false; + + for(int i=5;i*i<=num;i+=6) + if(num%i==0 or num%(i+2)==0) + return false; + + return true; +} + +int main() +{ + int num; + cout<<"Enter number to check:"; + cin>>num; + assert(num>0); + if(isPrime(num)) + cout<< num <<" is Prime Number\n"; + else + cout<< num <<" is not a Prime Number\n"; + +} \ No newline at end of file diff --git a/C++/MillerRabin.cpp b/C++/MillerRabin.cpp new file mode 100644 index 0000000..0096443 --- /dev/null +++ b/C++/MillerRabin.cpp @@ -0,0 +1,65 @@ +/* + + Miller Ranbin test Deterministic method for checking a prime number; + Time Complexity : O(12*log(n)); + Its Implementation + +*/ + +#include +using namespace std; +using u64 = uint64_t; +using u128 = __uint128_t; + +u64 bin_exp(u64 base, u64 e, u64 mod) { + u64 result = 1; + base %= mod; + while (e) { + if (e & 1) + result = (u128)result * base % mod; + base = (u128)base * base % mod; + e >>= 1; + } + return result; +} + +bool check_composite(u64 n, u64 a, u64 d, int s) { + u64 x = bin_exp(a, d, n); + if (x == 1 || x == n - 1) + return false; + for (int r = 1; r < s; r++) { + x = (u128)x * x % n; + if (x == n - 1) + return false; + } + return true; +}; + +bool MillerRabin(u64 n) { + if (n < 4) + return n > 1; + + int r = 0; u64 d = n - 1; + while ((d & 1) == 0) { + d >>= 1,r++; + } + + for (int a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) { + if (n == a) + return true; + if (check_composite(n, a, d, r)) + return false; + } + return true; +} +int main() +{ + u64 num; + cout<<"Enter number to check:"; + cin>>num; + assert(num>0); + if(MillerRabin(num)) + cout<< num <<" is Prime Number\n"; + else + cout<< num <<" is not a Prime Number\n"; +} \ No newline at end of file