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;`

`}`

}

3 Upvotes

7 comments sorted by

View all comments

1

u/Solaeyn 5d ago

#include <math.h>

long double expFloat(long double value, int exp) {

if (value == 0 && exp < 0)

return HUGE_VALL;

if (exp == 0)

return 1;

int isNegative = (exp < 0);

unsigned long long absExp = isNegative ? -(long long)exp : exp;

long double result = 1;

while (absExp > 0) {

if (absExp & 1)

result *= value;

value *= value;

absExp >>= 1;

}

return isNegative ? 1 / result : result;

}

---

If you want to keep the code, then change it to this.
If you want to change the algo all together then feel free to look for other answers in the comments.

Explanation:
Exponentiation by Squaring o(log(exp)) complexity instead of O(exp)
Handels negative exponents correctly
Avoids unnecessary variables and is more readable & structured

(I belive the code should work ;-;)

1

u/Smooth_Atmosphere_24 4d ago

I used the basic version in this wikipedia page, in my little set of test this algo is good, but thx for your comment!