Python: represent a number as a sum of prime numbers -


i need write algorithm, can represent number min sum of prime numbers:

for example: 8 -> [2, 2, 2, 2], [3, 5], [2, 3, 3] , need min len of => 2

i've written code, takes lot of time, because contains recursion. how can change improve time?

import sys  x = int(sys.stdin.readline())  def is_prime(n):     in range(2, n):         if n % == 0:             return false     return true  def decomposition(x):     result = []     in range(2, int(x/2 + 1)):         if x-a >= 2:             b = x -             pair = [a, b]             result.append(pair)     return result  def f(elem):     list_of_mins = []     if is_prime(elem) == true:         return 1     else:         pairs = decomposition(elem)         print(pairs)         a,b in pairs:             list_of_mins.append(f(a)+f(b))         return min(list_of_mins)   if str(int(x)).isdigit() , 2 <= int(x) <= 10 ** 9:     sum = []import sys  x = int(sys.stdin.readline())  def is_prime(n):     in range(2, n):         if n % == 0:             return false     return true  def decomposition(x):     result = []     in range(2, int(x/2 + 1)):         if x-a >= 2:             b = x -             pair = [a, b]             result.append(pair)     return result  def f(elem):     list_of_mins = []     if is_prime(elem) == true:         return 1     else:         pairs = decomposition(elem)         print(pairs)         a,b in pairs:             list_of_mins.append(f(a)+f(b))         return min(list_of_mins)   if str(int(x)).isdigit() , 2 <= int(x) <= 10 ** 9:     sum = []     print(f(x)) 

your is_prime function needs test divisors pow(n, 0.5)+1. means code be:

def is_prime(n):     in range(2, int(pow(n, 0.5)+1):         if n % == 0:             return false     return true 

this should speed algorithm significantly.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -