Sum of the integers from 1 to n

There is no need for a loop at all. You can use the triangular number formula:

n = int(input())
print(n * (n + 1) // 2)

A note about the division (//) (in Python 3): As you might know, there are two types of division operators in Python. In short, / will give a float result and // will give an int. In this case, we could use both operators, the only difference will be the returned type, but not the value. Since multiplying an odd with an even always gives an even number, dividing that by 2 will always be a whole number. In other words – n*(n+1) // 2 == n*(n+1) / 2 (but one would be x and the other x.0, respectively).

Leave a Comment