Mohamed_Elsharaky
Mohamed_Elsharaky

Reputation: 65

problem in summation of numbers between 1 to N in python

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?

Upvotes: 4

Views: 113

Answers (1)

pho
pho

Reputation: 25490

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.

Upvotes: 12

Related Questions