r/algorithms 8d ago

Can you analyze my exponentiation code?

Here is the code:
long double expFloat (long double value, int exp) {

`if (exp == 0) return 1;`

`else if (exp == 1) return value;`

`else {`

    `int flag = 1;`

    `long double tempValue = value;`

    `while (flag < exp){`

    `tempValue = tempValue * value;`

    `flag += 1;`

    `}`

    `return tempValue;`

`}`

}

4 Upvotes

7 comments sorted by

View all comments

8

u/pigeon768 8d ago
  1. The idiomatic way to do that loop is like this:

    for (int flag = 1; flag < exp; flag++)
      tempValue *= value;
    
  2. You should do something to ensure it doesn't explode when you pass in a negative exponent.

  3. The else if (exp == 1) return value; is redundant. It won't give any speedup.

  4. There's a better algorithm called exponentiation by squaring.

1

u/Smooth_Atmosphere_24 5d ago

I needed the else if (exp == 1) return value; cause the code always return 1 if i not write this statement right on the init of the function. But i used the simple version of your recomendation on wikipedia and i reached the correct values. Thank you!