I make functions of sum from 1 to last number as follows
def sum_way1(last_num):
sum_val = 0
for num in range(1, last_num+1):
sum_val=sum_val+num
return sum_val
def sum_way2(last_num):
return int((last_num*(last_num+1))/2)
But the result as follows:
- sum from 1 to 10000000000 : 50000000005000000000, execution time: 268.999 sec
- sum from 1 to 10000000000 : 50000000005000003584, execution time: 0.000 sec
The result of sum_way2 function is not exact.
Please let me know why I cannot get exact result of sum_way2 function?
Exact result:
- sum from 1 to 10000000000 : 50000000005000000000, execution time: 268.999 sec
- sum from 1 to 10000000000 : 50000000005000000000, execution time: 0.000 sec
The problem is caused by the fact that the
/operator in Python always returns afloatresult, even when its operands areint. So what you are doing here is:What you need to do is stay with
ints throughout your calculation. Use the integer division operator//instead:(P.S. if you're looking at an old book or website, which uses Python 2, then its
/operator did integer division if it had integer operands. That's no longer the case with Python 3.)