首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 計算 1¹ + 2² + 3³ + ... + nⁿ 級數和

     編輯:關於C#

計算 ∑(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 範圍

快速冪優化 O(log n)

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

大數支援:BigInteger

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...

數值增長參考

nnⁿ累加和
111
53,1253,413
1010,000,000,00010,405,071,317
15437,893,890,380,859,375≈4.38×10¹⁷
201.05×10²⁶≈1.05×10²⁶

效能比較 (n=1000, BigInteger)

  • 雙重迴圈:~1200ms
  • 快速冪 + BigInteger.Pow:~15ms
  • BigInteger.Pow 內部已優化,直接使用即可
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved