给定数字的因子和

-2 投票
2 回答
7869 浏览
提问于 2025-04-18 10:07

我写了一个代码,用来找出一个数字的因子。经过很多思考和尝试,我还是没办法得到这些因子的总和。我希望能通过递归的方式来计算这些因子的总和。以下是我的代码:

def p(n,c):
    s = 0
    if c >= n:
        return n
    if n % c == 0:
        s += c
        print(s,end=',')
    return p(n,c+1)
n = int(input('enter no:'))
c = 1
print(p(n,c))

2 个回答

0

这是你想要的输出吗?

使用全局变量,

s = 0 
def p(n,c):
   global s
   if c >= n:
      return n
   if n % c == 0:
      s += c
      print(s,end=',')
   return p(n,c+1) 
n = int(input('enter no:')) 
c = 1 
print(p(n,c))

输出结果

enter no:1,3,6,10,16,24,36,24
0

根据评论来看,这可能是你想要的内容:

sum([n for n in xrange(1,24) if 24 % n == 0])

为了让它更通用一些:

def sum_of_factors(x):
  return sum([n for n in xrange(1,x) if x % n == 0])

编辑:这里有一个递归版本:

def sum_of_factors(x, y=1):
  if (y >= x):
    return 0
  if (x % y == 0):
    return y + sum_of_factors(x, y + 1)
  return sum_of_factors(x, y + 1)

>>> sum_of_factors(24)
36

撰写回答