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 product of first N natural numbers is divisible by their sum in Python
Suppose we have a number n. We have to check whether the product of (1*2*...*n) is divisible by (1+2+...+n) or not.
So, if the input is like num = 5, then the output will be True as (1*2*3*4*5) = 120 and (1+2+3+4+5) = 15, and 120 is divisible by 15.
Mathematical Approach
Instead of calculating the actual product and sum, we can use a mathematical property. The product of first n natural numbers is n! (factorial), and the sum is n*(n+1)/2. The key insight is:
- If num + 1 is prime, then the factorial is NOT divisible by the sum
- If num + 1 is not prime, then the factorial IS divisible by the sum
Algorithm Steps
To solve this, we will follow these steps −
- If num + 1 is prime, then
- return False
- Return True
Implementation
Let us see the following implementation to get better understanding −
def isPrime(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
return False
return True
return False
def solve(num):
if isPrime(num + 1):
return False
return True
num = 5
print(f"For n = {num}:")
print(f"Product (factorial): {1*2*3*4*5}")
print(f"Sum: {1+2+3+4+5}")
print(f"Is divisible: {solve(num)}")
For n = 5: Product (factorial): 120 Sum: 15 Is divisible: True
Testing Multiple Cases
Let's test with different values to verify our approach ?
def isPrime(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
return False
return True
return False
def solve(num):
if isPrime(num + 1):
return False
return True
# Test multiple cases
test_cases = [3, 4, 5, 6, 7]
for n in test_cases:
result = solve(n)
print(f"n = {n}, n+1 = {n+1}, is_prime({n+1}) = {isPrime(n+1)}, divisible = {result}")
n = 3, n+1 = 4, is_prime(4) = False, divisible = True n = 4, n+1 = 5, is_prime(5) = True, divisible = False n = 5, n+1 = 6, is_prime(6) = False, divisible = True n = 6, n+1 = 7, is_prime(7) = True, divisible = False n = 7, n+1 = 8, is_prime(8) = False, divisible = True
Why This Works
The mathematical reasoning behind this approach is based on properties of factorials and prime numbers. When n+1 is prime, it creates a specific relationship between the factorial and the sum that prevents divisibility.
Conclusion
This problem can be solved efficiently by checking if n+1 is prime instead of computing large factorials. If n+1 is prime, the product is not divisible by the sum; otherwise, it is divisible.
