When I try to calculate the summation of numbers between 1 to N number with python I tried this code
N = int(input())
S = int(N*(N+1)/2)
print(S)
It works well until i tried to input N=641009859 the expected result should be= 205446819988104870 but the result is= 205446819988104864
What is the wrong in here?
N * (N + 1) / 2
does float division, and floating point numbers can't all be exactly represented. Do integer division: N * (N + 1) // 2
gives you what you expect (205446819988104870
)
Additional reading: What Every Computer Scientist Should Know About Floating-Point Arithmetic
Alternatively, you could bit-shift to the right by one bit (N >> 1
), which is the same as dividing by two because of how the binary system works.
(N >> 1) * (N + 1)
gives the same answer as before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With