TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
primality_test.cpp File Reference

Primality test implementation. More...

#include <iostream>
Include dependency graph for primality_test.cpp:

Go to the source code of this file.

Functions

bool IsPrime (int number)
 
int main ()
 

Detailed Description

Primality test implementation.

A simple and efficient implementation of a function to test if a number is prime, based on the fact that

‍Every Prime number, except 2 and 3, are of the form \(6k\pm1\) for integer values of k. This gives a 3x speed improvement.

Definition in file primality_test.cpp.

Function Documentation

◆ IsPrime()

bool IsPrime ( int number)

Check if a number is prime

Parameters
[in]numbernumber to check
Returns
true if prime else false

Definition at line 18 of file primality_test.cpp.

18 {
19 if (((!(number & 1)) && number != 2) || (number < 2) ||
20 (number % 3 == 0 && number != 3))
21 return false;
22
23 for (int k = 1; 36 * k * k - 12 * k < number; ++k) {
24 if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0))
25 return false;
26 }
27 return true;
28}
double k(double x)
Another test function.

◆ main()

int main ( void )

main function

Definition at line 31 of file primality_test.cpp.

31 {
32 // Main Function
33 std::cout << "Enter the value of n to check if Prime\n";
34 int n;
35 std::cin >> n;
36 if (IsPrime(n))
37 std::cout << n << " is Prime" << std::endl;
38 else
39 std::cout << n << " is not Prime" << std::endl;
40
41 return 0;
42}
bool IsPrime(int number)