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

Vasu Deo.S
  • 1,820
  • 1
  • 11
  • 23
Hubertto
  • 78
  • 8
  • 5
    `b /= 2` -- not integer divide in Python 3; compare to `b //= 2`. See https://stackoverflow.com/q/183853/2864740 – user2864740 May 18 '19 at 22:21

1 Answers1

2

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

b/=2

You want integer division:

b //= 2
Paul Evans
  • 27,315
  • 3
  • 37
  • 54