Prime Sum
Given an even number (greater than 2), return two prime numbers whose sum will be equal to given number.
NOTE: A solution will always exist.
Example:
Input : 4
Output: 2 + 2 = 4
If there are more than one solutions possible, return the lexicographically smaller solution.
If [a, b]
is one solution with a <= b
,
and [c,d]
is another solution with c <= d
, then
[a, b] < [c, d]
If a < c OR a==c AND b < d
.
Solution:
class Solution:
def primesum(self, A):
# write your method here
i = 2
primesum = []
while (i <= A - i):
if isprime(A - i):
primesum.append(i)
primesum.append(A - i)
return primesum
i = nextprime(i)
def isprime(k):
for i in range(2,int(k/2)):
if k % i == 0:
return 0
return 1
def nextprime(k):
while True:
k =k+1
if isprime(k):
return k
Comments
Post a Comment