提问人:Elio Baharan 提问时间:12/30/2022 最后编辑:khelwoodElio Baharan 更新时间:12/30/2022 访问量:91
质数之和 [已关闭]
sum of prime numbers [closed]
问:
我有一个练习:
编写一个程序,从输入中获取数字 n,并打印总和等于 n 的素数的所有情况。
例如:输入为 n = 13,输出为:
2 2 2 2 2 3
2 2 2 2 5
2 2 2 7
2 2 3 3 3
2 3 3 5
2 11
3 3 7
3 5 5
13
输出按词典法排序。
我只能编码来查找 1-n 之间的素数:
n = int(input())
lst = []
for i in range(2, n + 1):
isPrime = True
for j in range(2, i - 1):
if i % j == 0:
isPrime = False
if isPrime:
lst.append(i)
print(lst)
答:
-2赞
Nonlinear
12/30/2022
#1
这是我对这个问题的看法。
solution = []
primes_up_to_n = [2, 3, 5, 7, 11, 13]
def get_sums(primes, n, path):
global solution # keep track of solutions found so far.
if n < min(primes):
return # no more solutions are possible at this point
for prime in primes:
if n == prime:
solution.append(path+[prime])
get_sums(primes, n-prime, path+[prime])
get_sums(primes_up_to_n , 13, [])
k = [sorted(x) for x in solution] # order the solutions
print([*map(list, {*map(tuple, k)})]) # remove the duplicates
解释:
- 我们检查当前 N 是否在素数列表中。如果是,则表示这是一个解决方案,因此我们附加它。
path + [n]
- 我们递归地呼吁寻找进一步的解决方案。
这种方法的问题在于,该算法不区分 和 例如。因此,我们删除了最后两行中的此类重复项。
get_sums
[2, 2, 2, 2, 2, 3]
[2, 2, 2, 2, 3, 2]
代码输出:
[[2, 2, 2, 2, 2, 3],
[2, 2, 2, 7],
[2, 3, 3, 5],
[13],
[3, 3, 7],
[2, 2, 3, 3, 3],
[3, 5, 5],
[2, 2, 2, 2, 5],
[2, 11]]
评论
0赞
Karl Knechtel
12/30/2022
请阅读如何回答,不要简单地按照规范编写代码。像这样的问题不适合 Stack Overflow,需要解释答案中的代码。
0赞
Nonlinear
12/30/2022
@Karl Knechtel:嗯,很抱歉。我以为那个人已经试过了,但以后我会更加小心。对于解释,我编辑了我的帖子,我希望现在更清楚了。
评论