Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if N is a Factorial Prime in Python
A factorial prime is a prime number that is either one less than or one more than a factorial of any positive integer. For example, 719 is a factorial prime because 719 = 6! - 1 = 720 - 1, where 6! = 720.
In this article, we'll learn how to check if a given number N is a factorial prime in Python.
What is a Factorial Prime?
A factorial prime has the form n! ± 1, where:
- n! + 1 (one more than factorial)
- n! - 1 (one less than factorial)
The number must also be prime to qualify as a factorial prime.
Algorithm
To check if a number is a factorial prime, we follow these steps:
- First, check if the number is prime
- If not prime, return False
- Calculate factorials incrementally
- Check if the number equals factorial ± 1
- Return True if found, otherwise False
Implementation
Here's the complete solution to check if N is a factorial prime:
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 isFactorialPrime(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
# Test with example
num = 719
result = isFactorialPrime(num)
print(f"{num} is a factorial prime: {result}")
# Test with more examples
test_numbers = [2, 3, 5, 23, 719]
for n in test_numbers:
print(f"{n}: {isFactorialPrime(n)}")
719 is a factorial prime: True 2: True 3: True 5: True 23: True 719: True
How It Works
The algorithm works in two phases:
- Prime Check: Uses an optimized primality test that checks divisibility up to ?n
- Factorial Check: Calculates factorials incrementally and checks if the number equals n! ± 1
Example Verification
Let's verify why 719 is a factorial prime:
import math
# Check if 719 is prime
def verify_factorial_prime():
num = 719
# Calculate factorials to find the match
for i in range(1, 10):
factorial = math.factorial(i)
if num == factorial - 1:
print(f"{num} = {i}! - 1 = {factorial} - 1")
return True
elif num == factorial + 1:
print(f"{num} = {i}! + 1 = {factorial} + 1")
return True
return False
verify_factorial_prime()
719 = 6! - 1 = 720 - 1
Time Complexity
The time complexity is O(?n + k), where:
- O(?n) for the primality test
- O(k) for factorial calculation, where k is the number of factorials to check
Conclusion
A factorial prime is a prime number that equals n! ± 1 for some positive integer n. Our solution efficiently checks both primality and the factorial condition to determine if a number is a factorial prime.
