# Same code works on C++ but not in python

Continuing the discussion from Same code works on C++ but not in python:

Since the contest is now over i am uploading my codes kindly have a look and tell me where I went a wrong

Working C++ Code:-

https://www.codechef.com/viewsolution/34280955

Partially working Python code:-

https://www.codechef.com/viewsolution/34281082

using namespace std;

int main()
{
int t;
long int n;
ios::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);
cin>>t;
while(t--)
{
cin>>n;
while(n%2==0)
{
n /= 2;
}

cout<<n/2<<endl;

}
return 0;
}

PYTHON CODE

t = int(input())
while t > 0:
ts = int(input())
while ts % 2 == 0:
ts /= 2
print(int(ts / 2))
t -= 1


@sachin_01 same thing happened with me also , Anyone can tell me why it happened

i think there is a glitch in their system regarding python 3

Let’s assume that the number is 10. It is even. If you use /= on 10, instead of 5, you get 5.0.
This is disastrous because the answer should be \text{floor(2.5)} = 2. But your python code gives 2.5 which is clearly wrong. Use integer division by using two brackets like // instead of /.

t = int(input())
while t > 0:
ts = int(input())
while ts % 2 == 0:
ts = ts // 2
print(ts // 2)
t -= 1

1 Like

Yes correct!

as pointed by @anon53253486 use integer division (// in place of /)

1 Like

Unlike C++, Python ‘/’ gives float division while C++ gives floor division. To get floor division in python use ‘//’.

1 Like

@anon53253486 I think that is not the problem here as @sachin_01 used the int type conversion while printing the output.

1 Like

To clarify, I got AC with the code I attached after my answer. I’m not sure if int() floors the value or rounds it. So I used integer division.

1 Like

@anon53253486 i used floor then also it was showing partially correct ans
here’s my code
https://www.codechef.com/viewsolution/33814827

1 Like

print(int(39/10))
print(39//10)

I just checked, these two operations give the exact same answer. Python floors division value.

1 Like

int () also floors it

Never use int(a/b)…it gives precision errors.
Always use a//b. I have experienced this.

4 Likes

not always

it doesnt matter bro as i have used int() while printing it floors the input

1 Like

I agree. I have experience as well. The only place I use int() in python is n = int(input()). It is useless otherwise (not always, but for this scenario, definitely).

this made sense i replaced / with //
now i am getting correct answer. my program finally WORKS

but can you plz elaborate why int() doesnt give correct answer

Not necessarily. Always use // for arithmetic operations.