简体   繁体   中英

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

I have a ulong value that I need to raise to a high power, but Math.Pow does not successfully produce a correct output.

My c# code:

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

The output to screen is 0. How can I perform this calculation and obtain a correct result?

Yes, it is possible to compute that number, using the specialized BigInteger class. It's hopeless to try and do this with a ushort , which has a width of 16 bits.

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

Outputs

43056151396124937171542222696555900626431494491043369510338912076154406943108
..
8614367506747618876018379290109

By the way, you'd need 330,837 bits to store the result.

如果您打算使用非常大的数字,请查找BigInteger

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM