Reputation: 108
I have function in C++ that returns positive number a
magnified b
times. In C++ this function runs with no errors but I want to use this function in Python. Could anyone tell why this function returns result in C++
but does not return it in Python or where I made a mistake in Python code?
I know that I can write this function in many other ways and that this function may not be the best solution but what is wrong with THIS particular example? What I have to do to run this in Python without writing new, better function obviously. Why I can run this code in C++ but not in Python?
C++ CODE:-
int exp(int a,int b){
int result=1;
while(b!=0){
if(b%2==1){
result*=a;
}
b/=2;
a*=a;
}
return result;
}
PYTHON CODE:-
def exp(a,b):
result=1
while b!=0:
if b%2==1:
result*=a
b/=2
a*=a
return result
Is something wrong with while condition in Python???
Upvotes: 2
Views: 167
Reputation: 27577
You're using floating point division in the Python code:
b/=2
You want integer division:
b //= 2
Upvotes: 2