Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function for sums of integers

Wrote a python program that added up numbers from 1 to a given number using the Gauss equation. It worked for 100 and 10 but when I do 3 it says the sum is 4 instead of 6. The equation works out in my head, did I mess up the code?

def numberSum(num): 

    nim = int(num)
    num = (nim/2)*(nim+1)
    return num    

print numberSum(raw_input())  
like image 305
admiralmattbar Avatar asked Aug 10 '26 07:08

admiralmattbar


1 Answers

from __future__ import division

def number_sum(num):
    """
    Return sum of 1 .. num
    """
    return num * (num + 1) // 2

num = int(raw_input(": "))
print(number_sum(num))

Things I changed:

  • number_sum should not be responsible for type-casting input; if it expects a number, you should give it some kind of number, not a string.

  • if num is an int, then either num or num + 1 is even, ie dividing num * (num + 1) by 2 will result in an int. This is not necessarily true of num; therefore you should divide the product by 2, not num, if you want an integer result.

  • in Python 2.6+, from __future__ import division makes / always return a float result and // always return an int result, consistent with Python 3.x

like image 72
Hugh Bothwell Avatar answered Aug 13 '26 09:08

Hugh Bothwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!