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
Selected Reading
Program to check n can be represented as sum of k primes or not in Python
Suppose we have two inputs n and k. We have to check whether n can be represented as a sum of k number of prime values or not.
So, if the input is like n = 30 k = 3, then the output will be True because 30 can be represented like 2 + 11 + 17.
Algorithm
To solve this, we will follow these steps ?
- if n < k*2, then return False
- if k > 2, then return True
- if k is same as 2, then
- if n is even, then return True
- if (n-2) is prime, then return True
- return False
- if n is prime, then return True
- return False
Implementation
Let us see the following implementation to get better understanding ?
def check_prime(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
return False
return True
return False
def solve(n, k):
if n < k*2:
return False
if k > 2:
return True
if k == 2:
if n%2 == 0:
return True
if check_prime(n-2):
return True
return False
if check_prime(n):
return True
return False
n = 30
k = 3
print(solve(n, k))
The output of the above code is ?
True
How It Works
The algorithm is based on Goldbach's conjecture and number theory principles:
- Base case: If n < 2k, impossible since smallest prime is 2
- k > 2: Always possible by using (k-2) copies of 2 plus representing remaining as sum of 2 primes
- k = 2: Use Goldbach's conjecture ? every even number > 2 can be expressed as sum of two primes
- k = 1: Check if n itself is prime
Example with Different Inputs
def check_prime(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
return False
return True
return False
def solve(n, k):
if n < k*2:
return False
if k > 2:
return True
if k == 2:
if n%2 == 0:
return True
if check_prime(n-2):
return True
return False
if check_prime(n):
return True
return False
# Test different cases
test_cases = [(30, 3), (10, 2), (7, 1), (15, 4)]
for n, k in test_cases:
result = solve(n, k)
print(f"n={n}, k={k}: {result}")
n=30, k=3: True n=10, k=2: True n=7, k=1: True n=15, k=4: True
Conclusion
This algorithm efficiently determines if a number can be represented as sum of k primes using Goldbach's conjecture and number theory principles. The time complexity depends on the primality check function.
Advertisements
