Given a natural number A, I want to find all the pairs of natural numbers (B,C) so that B*C*(C+1) = A

后端 未结 3 1489
情书的邮戳
情书的邮戳 2021-02-06 08:45

What\'s the fastest way to do it?

My simple aproach:

for (C = 1;C

        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-06 09:28

    This python seems to work:

    from __future__ import division
    from math import sqrt
    
    def bcc1(a):
        ans = []
        if a % 2: return ans   # for odd a
        for b in range(1, a // 2 + 1):
            c = max(1, int(sqrt(a / b)))
            if b*c*(c+1) == a: 
                ans.append((b,c))
        return ans
    
    for a in range(2, 51, 2):
        print('a: %2i -> (b, c): %r' % (a, bcc1(a)))
    

    The output produced is:

    a:  2 -> (b, c): [(1, 1)]
    a:  4 -> (b, c): [(2, 1)]
    a:  6 -> (b, c): [(1, 2), (3, 1)]
    a:  8 -> (b, c): [(4, 1)]
    a: 10 -> (b, c): [(5, 1)]
    a: 12 -> (b, c): [(1, 3), (2, 2), (6, 1)]
    a: 14 -> (b, c): [(7, 1)]
    a: 16 -> (b, c): [(8, 1)]
    a: 18 -> (b, c): [(3, 2), (9, 1)]
    a: 20 -> (b, c): [(1, 4), (10, 1)]
    a: 22 -> (b, c): [(11, 1)]
    a: 24 -> (b, c): [(2, 3), (4, 2), (12, 1)]
    a: 26 -> (b, c): [(13, 1)]
    a: 28 -> (b, c): [(14, 1)]
    a: 30 -> (b, c): [(1, 5), (5, 2), (15, 1)]
    a: 32 -> (b, c): [(16, 1)]
    a: 34 -> (b, c): [(17, 1)]
    a: 36 -> (b, c): [(3, 3), (6, 2), (18, 1)]
    a: 38 -> (b, c): [(19, 1)]
    a: 40 -> (b, c): [(2, 4), (20, 1)]
    a: 42 -> (b, c): [(1, 6), (7, 2), (21, 1)]
    a: 44 -> (b, c): [(22, 1)]
    a: 46 -> (b, c): [(23, 1)]
    a: 48 -> (b, c): [(4, 3), (8, 2), (24, 1)]
    a: 50 -> (b, c): [(25, 1)]
    

提交回复
热议问题