在C#中處理斐波那契數列的大數問題,可以使用BigInteger類
using System;
using System.Numerics;
class FibonacciBigNumber
{
static void Main()
{
int n;
Console.Write("請輸入需要計算的斐波那契數列項數:");
n = int.Parse(Console.ReadLine());
BigInteger result = CalculateFibonacci(n);
Console.WriteLine($"第 {n} 項斐波那契數列的值為:{result}");
}
static BigInteger CalculateFibonacci(int n)
{
if (n <= 1) return n;
BigInteger a = 0;
BigInteger b = 1;
BigInteger temp;
for (int i = 2; i <= n; i++)
{
temp = a + b;
a = b;
b = temp;
}
return b;
}
}
這個程序首先接收用戶輸入的斐波那契數列項數,然后調用CalculateFibonacci方法計算相應的值。在CalculateFibonacci方法中,我們使用BigInteger類型來存儲大數值。通過迭代的方式計算斐波那契數列,最后返回結果。