1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| #include <stdio.h> #include <limits.h>
long long fastPowerInt(long long base, int exponent) { if (exponent == 0) { return 1; }
if (base == 0) { if (exponent < 0) { printf("错误:0 的负数次幂无意义!\n"); return LLONG_MIN; } return 0; }
if (exponent < 0) { if (base == 1) return 1; if (base == -1) { return (exponent % 2 == 0) ? 1 : -1; } return 0; }
long long absExponent = exponent; long long result = 1; long long currentBase = base;
while (absExponent > 0) { if (absExponent % 2 == 1) { if (currentBase != 0 && result > LLONG_MAX / currentBase && currentBase > 0) { printf("警告:计算结果溢出 long long 范围!\n"); return LLONG_MAX; } if (currentBase != 0 && result < LLONG_MIN / currentBase && currentBase < 0) { printf("警告:计算结果溢出 long long 范围!\n"); return LLONG_MIN; } result *= currentBase; }
if (absExponent > 1) { if (currentBase > 0 && currentBase > 3037000499LL) { printf("警告:中间计算过程底数平方溢出!\n"); return (exponent % 2 != 0 && result != 1) ? LLONG_MAX : LLONG_MAX; } if (currentBase < -3037000499LL) { printf("警告:中间计算过程底数平方溢出!\n"); return LLONG_MIN; } currentBase *= currentBase; }
absExponent /= 2; }
return result; }
int main() { printf("--- 整数快速幂测试 (long long) ---\n");
printf("2^10 = %lld\n", fastPowerInt(2, 10)); printf("3^4 = %lld\n", fastPowerInt(3, 4)); printf("5^0 = %lld\n", fastPowerInt(5, 0)); printf("0^5 = %lld\n", fastPowerInt(0, 5)); printf("2^-3 = %lld (整数除法应为0)\n", fastPowerInt(2, -3)); printf("1^-100 = %lld\n", fastPowerInt(1, -100)); printf("-1^-3 = %lld\n", fastPowerInt(-1, -3)); printf("-1^-4 = %lld\n", fastPowerInt(-1, -4));
printf("0^-2 = %lld (应报错)\n", fastPowerInt(0, -2)); printf("0^0 = %lld (约定为1)\n", fastPowerInt(0, 0));
printf("10^18 = %lld\n", fastPowerInt(10, 18));
printf("(-1)^INT_MIN = %lld (应为1)\n", fastPowerInt(-1, -2147483648)); return 0; }
|