Search code examples
c#powulong

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?


Solution

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