Fix calculation of 2**30

In exponent(), 'base *= base;' should not run
when base is 65536, since it overflows an int32_t.

This also optimizes exponent() based on
gcc and clang -O3 test cases in godbolt.org.
This commit is contained in:
Rangi
2021-02-17 09:25:02 -05:00
parent d049ffc0f0
commit 748e7dd4c7
3 changed files with 11 additions and 5 deletions

View File

@@ -21,14 +21,16 @@
#include "extern/err.h"
static int32_t exponent(int32_t base, int32_t power)
static int32_t exponent(int32_t base, uint32_t power)
{
int32_t result = 1;
while (power) {
for (;;) {
if (power % 2)
result *= base;
power /= 2;
if (!power)
break;
base *= base;
}