2

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???

1

1 Answer 1

2

You're using floating point division in the Python code:

b/=2

You want integer division:

b //= 2
Sign up to request clarification or add additional context in comments.

4 Comments

Only for python 3.x as previous versions worked well with / and treated it's output as integer.
@VasuDeo.S Question tagged with python3.
I was just trying to inform the readers of this answer, if they are not aware of this fact.
Yes I am using python-3.x now, anyway thanks all of u guys, it helped. That was really simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.