Check if N is a Factorial Prime in Python


Suppose we have a number n, we have to check whether n is a Factorial prime or not. As we know a number is said to be a factorial prime when it is a prime number that is one less than or one more than a factorial of any number.

So, if the input is like n = 719, then the output will be True as 719 = 720 - 1 = 6! - 1

To solve this, we will follow these steps −

  • if num is not a prime, then
    • return False
  • factorial := 1, i := 1
  • while factorial <= num + 1, do
    • factorial := factorial * i
    • if num + 1 is same as factorial or num - 1 is same as factorial, then
      • return True
    • i := i + 1
  • return False

Example

Let us see the following implementation to get better understanding −

 Live Demo

from math import sqrt
def isPrime(num) :
   if num <= 1:
      return False
   if num <= 3 :
      return True
   if num % 2 == 0 or num % 3 == 0:
      return False
   for i in range(5, int(sqrt(num)) + 1, 6) :
      if num % i == 0 or num % (i + 2) == 0:
         return False
   return True
def solve(num) :
   if not isPrime(num) :
      return False
   factorial = 1
   i = 1
   while factorial <= num + 1:
      factorial *= i
      if num + 1 == factorial or num - 1 == factorial :
         return True
      i += 1
   return False
num = 719
print(solve(num))

Input

719

Output

True

Updated on: 19-Jan-2021

395 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements