素数在python中怎么表示_Python:将一个数表示为素数的和

我需要写一个算法,把一个数表示为素数的最小和:

例如:

8->[2,2,2],[3,5],[2,3,3]

我需要得到这个的最小长度=>2

我已经编写了代码,但它需要很多时间,因为它包含递归。我如何改变它来提高时间?在import sys

x = int(sys.stdin.readline())

def is_prime(n):

for i in range(2, n):

if n % i == 0:

return False

return True

def decomposition(x):

result = []

for a in range(2, int(x/2 + 1)):

if x-a >= 2:

b = x - a

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)

for a,b in pairs:

list_of_mins.append(f(a)+f(b))

return min(list_of_mins)

if str(int(x)).isdigit() and 2 <= int(x) <= 10 ** 9:

sum = []import sys

x = int(sys.stdin.readline())

def is_prime(n):

for i in range(2, n):

if n % i == 0:

return False

return True

def decomposition(x):

result = []

for a in range(2, int(x/2 + 1)):

if x-a >= 2:

b = x - a

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)

for a,b in pairs:

list_of_mins.append(f(a)+f(b))

return min(list_of_mins)

if str(int(x)).isdigit() and 2 <= int(x) <= 10 ** 9:

sum = []

print(f(x))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值