Can somebody solve this problem on Python ?
A positive integer m can be partitioned as primes if it can be written as p + q where p > 0, q > 0 and both p and q are prime numbers.
Write a Python function that takes an integer m as input and returns True if m can be partitioned as primes and False otherwise.
Tried this, but does not work for all testcases, for example it should return True for 3432, it returns False.
def partition(num):
primelist=[]
for i in range(2,num + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
for x in primelist:
y= num-x
for z in range(2,y):
if y%z == 0:
return False
return True
The error lies in the second for loop. You are looping through possible primes
x, and wish to then check thaty = num - xis also prime.The error in your logic is that in the second for loop, if the first element in the loop
y = num - xis not prime, it will returnFalse, without checking any of the other possible values.You could correct this by moving the
return Falsestatement out one loop, but since you have already generated a list of primes less thannum,primelist(and sincey = num - x, (if primeyexists) it will be in this list), you can just check for membership of the list:Note: I would advise making the logic of your script more modular, separating out the prime list generator into its own function: