我如何将一个非常大的数字提升到一个非常大的幂?

How do I raise a really big number to a really big power?

我有一个 ulong 值需要提高到较高的幂,但是 Math.Pow 没有成功产生正确的输出。

我的 C# 代码:

 ulong a = 9123456789;
 ulong b = (ulong)Math.Pow(a, 9999);
 Console.WriteLine(b);

屏幕输出为 0。如何执行此计算并获得正确的结果?

如果您要处理非常大的数字,请查找 BigInteger

是的,可以使用专门的 BigInteger class 来计算该数字。用宽度为 16 位的 ushort 来尝试这样做是没有希望的。

using System;
using System.Collections;
using System.Numerics;

public class Test 
{
    public static void Main(string[] args)
    {
        BigInteger a = 9123456789;
        BigInteger b = BigInteger.Pow(a, 9999);

        //Output this number if you're feeling lucky.
        Console.WriteLine(b);
    }
}

产出

43056151396124937171542222696555900626431494491043369510338912076154406943108
..
8614367506747618876018379290109

顺便说一句,您需要 330,837 位来存储结果。