Search code examples
pythonloopsnested-loops

All possible way of adding up number in a sequence so that it becomes a given number


I was given range n and number k. Count the possible ways so that two (not identical) number in that range add up to number k. And can this be done without nested loops? Here's my approach, the only thing is I'm using a nested loop, which takes times and not computer-friendly. Opposite pairs like (A, B) and (B, A) still count as 1.

n, k = int(input()), int(input())
cnt = 0
for i in range(1, n+1):
    for s in range(1, n+1):
        if i == 1 and s == 1 or i == n+1 and s==n+1:
            pass
        else:
            if i+s==k:
                cnt += 1
print(int(cnt/2))

example inputs (first line is n, second is k)

8
5

explanation(1, 4 and 2, 3), so I should be printing 2


Solution

  • You only need a single loop for this:

    n = int(input('N: ')) # range 1 to n
    k = int(input('K: '))
    r = set(range(1, n+1))
    c = 0
    
    while r:
        if k - r.pop() in r:
            c += 1
    
    print(c)