1

In python for a problem https://www.spoj.com/problems/APM i used

t = int(input())
while t > 0:
    n= int(input())

    if n%2 == 0:
        print(-1)
    else:
        n = int((n+1)/2)
        print(n,n-1)
    t -= 1 

this code and rejected,

but for this :

t = int(input())

while t > 0:
    n= int(input())

    if n%2 == 0:
        print(-1)
    else:
        n = (n+1)//2
        print(n,n-1)
    t -= 1  

accepted, my question is why int((n+1)/2) gives different ans then (n+1)//2 at large number n< 10^18?

gaurav
  • 415
  • 5
  • 12

3 Answers3

4

Even though for small n, it is true that int(n*(n-1)/2) == n*(n-1)//2, that can fail for large n. The reason why is that / is floating point division, which can result in loss of information, information that int() can't recover:

>>> n = 10**18 - 1
>>> n*(n-1)
999999999999999997000000000000000002
>>> n*(n-1)//2
499999999999999998500000000000000001
>>> n*(n-1)/2
5e+35
>>> int(n*(n-1)/2)
500000000000000021210318687008980992

The loss of information can be seen in 5e+35 vs. 499999999999999998500000000000000001

John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • 1
    @gaurav It is integer division. Mathematically, it is the same as `int( / )` but is guaranteed to work for all integers, even ones with hundreds of digits. This is because the computation involves only integers, and doesn't compute an intermediate float. – John Coleman May 10 '20 at 11:12
1

Consider:

import sys

print(sys.float_info)

i=(10**17+2)/2
j=(10**16+2)/2

print(i,j)
print(type(i), type(j))

i,j=int(i),int(j)

print(i,j)
print(type(i), type(j))

Although you're far from reaching float limits - you reached limit of digits that float can store - so everything after this limit will just get truncated in the exponential notation - so it will be the same magnitude of values, yet all the excessive numbers from the back will be 0.

Conclusion:

Converting types requires great care to detail - just use \\ instead.

Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
0

The double slash in Python performs integer division, whereas the single slash performs regular old division which may yield a float.

I don't see anywhere in the question you linked to that requires you to have an integer answer, but I imagine the author wanted it to be this way to prevent any floating point precision errors preventing the automated test cases from being successful.

Mathyou
  • 651
  • 2
  • 10
  • 28