This program works by pairing the numbers together from the end to the beginning. For example, to find the sum of the list 1, 2, 3, 4, 5, 6
, you can pair 1
and 6
to make 7, 2
and 5
to make 7, and 3
and 4
to make 7. See a pattern? (hint: the pairs always add up to the sum of the first and the last).
This program also includes an adjustment for lists with an odd number of elements. For example, in the list 1, 2, 3
, one needs to add the additional middle number that cannot be in a pair. 1
and 3
can pair to 4, but you'll need to add the unpaired 2
to the sum.
Now that you understand it, all you need to do is extract it into a function. Like this:
def consecutiveSum(num2):
num1 = 1
return int((num2*(num2+1)/2) - (num1*(num1+1)/2) + num1)
print(consecutiveSum(10)) # => 55
print(consecutiveSum(100)) # => 5050
Jiho Kim's answer also points out that this can be optimized a bit. See his answer too.