Given an integer N where 1 ≤ N ≤ 105, the task is to find whether (N-1)! % N = N – 1 or not.
Input: N = 3
Here, n = 3 so (3 – 1)! = 2! = 2
=> 2 % 3 = 2 which is N – 1 itself
Input: N = 4
Here, n = 4 so (4 – 1)! = 3! = 6
=> 6 % 3 = 0 which is not N – 1.
Naive approach: To solve the question mentioned above the naive method is to find (N – 1)! and check if (N – 1)! % N = N – 1 or not. But this approach will cause overflow since 1 ≤ N ≤ 105
Efficient approach: To solve the above problem in an optimal way we will use Wilson’s theorem which 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
So, now we just have to check if N is a prime number(including 1) or not.
Below is the implementation of the above approach:
Time Complexity: O(sqrt(N))
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find remainder of array multiplication divided by n
- Generate Array whose sum of all K-size subarrays divided by N leaves remainder X
- Find the last digit when factorial of A divides factorial of B
- Largest power of k in n! (factorial) where k may not be prime
- Check if N is a Factorial Prime
- Check whether factorial of N is divisible by sum of first N natural numbers
- Check if factorial of N is divisible by the sum of squares of first N natural numbers
- Check if a given number is factorial of any number
- Check if N-factorial is divisible by X^Y
- Chinese Remainder Theorem | Set 2 (Inverse Modulo based Implementation)
- Remainder with 7 for large numbers
- Program to find remainder without using modulo or % operator
- Using Chinese Remainder Theorem to Combine Modular equations
- Quotient - Remainder Sort
- Find N % 4 (Remainder with 4) for a large value of N
- Quotient Remainder Theorem
- Count digits in a factorial | Set 2
- Count trailing zeroes in factorial of a number
- Factorial of a large number
- Count factorial numbers in a given range
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.