3

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())  
Daniel Roseman
  • 541,889
  • 55
  • 754
  • 786

2 Answers2

4
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

Hugh Bothwell
  • 50,702
  • 6
  • 75
  • 95
  • I think this answer is the most correct one, as the sum of integers should be integer as well and not a float. And it will also work properly in Python 3 – MaxU Feb 21 '16 at 21:45
3

I suppose you are working with python2, cause by default it applies integer division like other languages. Besides, you can notice this feature in this post Integer division in python 2 and python 3.

To solve your problem you can follow the next approach:

def numberSum(num): 
    nim = int(num)
    return ((nim * 1.0) / 2) * (nim + 1)    

print numberSum(raw_input())  
Community
  • 1
  • 1
Alberto Bonsanto
  • 15,350
  • 8
  • 56
  • 90