C++ Program to Implement Fermat Primality Test

«
»
This C++ Program demonstrates the implementation of Fermat Primality Test.

Here is source code of the C++ Program to demonstrate the implementation of Fermat Primality Test. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* 
  2.  * C++ Program to Implement Fermat Primality Test
  3.  */
  4. #include <cstring>
  5. #include <iostream>
  6. #include <cstdlib>
  7. #define ll long long
  8. using namespace std;
  9. /* 
  10.  * modular exponentiation
  11.  */
  12. ll modulo(ll base, ll exponent, ll mod)
  13. {
  14.     ll x = 1;
  15.     ll y = base;
  16.     while (exponent > 0)
  17.     {
  18.         if (exponent % 2 == 1)
  19.             x = (x * y) % mod;
  20.         y = (y * y) % mod;
  21.         exponent = exponent / 2;
  22.     }
  23.     return x % mod;
  24. }
  25.  
  26. /* 
  27.  * Fermat's test for checking primality 
  28.  */
  29. bool Fermat(ll p, int iterations)
  30. {
  31.     if (p == 1)
  32.     {
  33.         return false;
  34.     }
  35.     for (int i = 0; i < iterations; i++)
  36.     {
  37.         ll a = rand() % (p - 1) + 1; 
  38.         if (modulo(a, p - 1, p) != 1)
  39.         { 
  40.             return false;
  41.         }
  42.     }
  43.     return true;
  44. }
  45. /* 
  46.  * Main
  47.  */
  48. int main()
  49. {
  50.     int iteration = 50;
  51.     ll num;
  52.     cout<<"Enter integer to test primality: ";
  53.     cin>>num;
  54.     if (Fermat(num, iteration))
  55.         cout<<num<<" is prime"<<endl;
  56.     else
  57.         cout<<num<<" is not prime"<<endl;
  58.     return 0;
  59. }

advertisement
$ g++ fermat_primality.cpp
$ a.out
 
Enter integer to test primality: 479001599
479001599 is prime
 
------------------
(program exited with code: 1)
Press return to continue

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn