Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading