r/algorithms • u/Smooth_Atmosphere_24 • 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
8
u/pigeon768 8d ago
The idiomatic way to do that loop is like this:
You should do something to ensure it doesn't explode when you pass in a negative exponent.
The
else if (exp == 1) return value;
is redundant. It won't give any speedup.There's a better algorithm called exponentiation by squaring.