python 求和为正整数n的连续整数序列

原文:http://bbs.chinaunix.net/thread-4191271-1-1.html

  1. n = 100
  2. s = range(1, n)
  3. d = [s[i:i+j] for i in range(len(s)) for j in range(1, len(s)-i+1) if sum(s[i:i+j]) == n]

  4. print d
 思路不错,就是执行起来,如果数够大,效率有点低,还能再改进改进吗?


def N2S(n):
    x = int(n / 2) + 1 + 1
    s = [0]
    r = []

    for i in range(1, x):
        s.append(s[-1] + i)
    for i in range(1, x):
        k = n + s[i - 1]
        for j in range(i + 1, x):
            if s[j] < k: continue
            if s[j] == k: r.append(range(i, j + 1))
            break

    for i in r:
        print(list(i))


N2S(15)

你可能感兴趣的:(python)