計算 ∑(i=1 to n) iⁱ 需處理快速增長的冪次結果。雙重迴圈直觀但效率低,建議使用快速冪演算法或 BigInteger 處理大數。
public long SumPowersNaive(int n) {
long sum = 0;
for (int i = 1; i <= n; i++) {
long term = 1;
for (int j = 1; j <= i; j++) term *= i; // i 的 i 次方
sum += term;
}
return sum;
}
// n=10 時已超過 long 範圍
public long FastPower(long baseNum, int exp) {
long result = 1;
while (exp > 0) {
if ((exp & 1) == 1) result *= baseNum;
baseNum *= baseNum;
exp >>= 1;
}
return result;
}
public long SumPowersOptimized(int n) {
long sum = 0;
for (int i = 1; i <= n; i++) {
sum += FastPower(i, i);
}
return sum;
}
using System.Numerics;
public BigInteger SumPowersBigInt(int n) {
BigInteger sum = 0;
for (int i = 1; i <= n; i++) {
sum += BigInteger.Pow(i, i);
}
return sum;
}
// n=20 可正確計算
// 結果:1^1 + 2^2 + ... + 20^20 = 38888888888888888888888888888888888888888...
| n | nⁿ | 累加和 |
|---|---|---|
| 1 | 1 | 1 |
| 5 | 3,125 | 3,413 |
| 10 | 10,000,000,000 | 10,405,071,317 |
| 15 | 437,893,890,380,859,375 | ≈4.38×10¹⁷ |
| 20 | 1.05×10²⁶ | ≈1.05×10²⁶ |
BigInteger.Pow 內部已優化,直接使用即可