# Implementation of Wilson Primality test

Given a number N, the task is to check if it is prime or not using Wilson Primality Test. Print ‘1’ isf the number is prime, else print ‘0’.

Wilson’s theorem states that a natural number p > 1 is a prime number if and only if

(p - 1) ! ≡ -1 mod p OR (p - 1) ! ≡ (p-1) mod p

Examples:

Input: p = 5 Output: Yes (p - 1)! = 24 24 % 5 = 4 Input: p = 7 Output: Yes (p-1)! = 6! = 720 720 % 7 = 6

Below is the implementation of Wilson Primality Test

`// C++ implementation to check if a number is ` `// prime or not using Wilson Primality Test ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Function to calculate the factorial ` `long` `fact(` `const` `int` `& p) ` `{ ` ` ` `if` `(p <= 1) ` ` ` `return` `1; ` ` ` `return` `p * fact(p - 1); ` `} ` ` ` `// Function to check if the ` `// number is prime or not ` `bool` `isPrime(` `const` `int` `& p) ` `{ ` ` ` `if` `(p == 4) ` ` ` `return` `false` `; ` ` ` `return` `bool` `(fact(p >> 1) % p); ` `} ` ` ` `// Driver code ` `int` `main() ` `{ ` ` ` `cout << isPrime(127); ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

**Output:**

1

**How does it work?**

- We can quickly check result for p = 2 or p = 3.
- For p > 3: If p is composite, then its positive divisors are among the integers 1, 2, 3, 4, … , p-1 and it is clear that
**gcd((p-1)!,p) > 1**, so we can not have (p-1)! = -1 (mod p). -
Now let us see how it is exactly -1 when p is a prime. If p is a prime, then all numbers in [1, p-1] are relatively prime to p. And for every number x in range [2, p-2], there must exist a pair y such that (x*y)%p = 1. So
[1 * 2 * 3 * ... (p-1)]%p = [1 * 1 * 1 ... (p-1)] // Group all x and y in [2..p-2] // such that (x*y)%p = 1 = (p-1)

## Recommended Posts:

- AKS Primality Test
- Lucas Primality Test
- Vantieghems Theorem for Primality Test
- Primality Test | Set 2 (Fermat Method)
- Primality Test | Set 3 (Miller–Rabin)
- Primality Test | Set 4 (Solovay-Strassen)
- Primality test for the sum of digits at odd places of a number
- Primality Test | Set 1 (Introduction and School Method)
- Primality Test | Set 5(Using Lucas-Lehmer Series)
- Wilson's Theorem
- Implementation of K Nearest Neighbors
- Lychrel Number Implementation
- Fizz Buzz Implementation
- Cubic Bezier Curve Implementation in C
- Travelling Salesman Problem implementation using BackTracking

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.