How can I use bigint with C#?

泄露秘密 提交于 2019-11-28 09:17:15

You can use System.Numerics.BigInteger (add a reference to System.Numerics assembly). As mentioned in the comments this might not be the right approach though.

Native support for big integers has been introduced in .NET 4.0. Just add an assembly reference to System.Numerics, add a using System.Numerics; declaration at the top of your code file, and you’re good to go. The type you’re after is BigInteger.

Sunil Chandurkar

Here's using BigInteger. This method Prints Numbers in the Fibonacci Sequence up to n.

public static void FibonacciSequence(int n)
{
    /** BigInteger easily holds the first 1000 numbers in the Fibonacci Sequence. **/
    List<BigInteger> fibonacci = new List<BigInteger>();
    fibonacci.Add(0);
    fibonacci.Add(1);
    BigInteger i = 2;
    while(i < n)
    {                
        int first = (int)i - 2;
        int second = (int) i - 1;

        BigInteger firstNumber =  fibonacci[first];
        BigInteger secondNumber = fibonacci[second];
        BigInteger sum = firstNumber + secondNumber;
        fibonacci.Add(sum);
        i++;
    }         

    foreach (BigInteger f in fibonacci) { Console.WriteLine(f); }
}

BigInteger is available in .NET 4.0 or later. There are some third-party implementations as well (In case you are using an earlier version of the framework).

Kishore Kumar

Better use System.Numerics.BigInteger.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!