3

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?

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246

2 Answers2

9

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.

Maximilian Gerhardt
  • 5,188
  • 3
  • 28
  • 61
  • 1
    You need explicitly include the `System.Numerics.dll` in your project. Go in visual studio, right-click on "References" in side the project, go to "Assemblies", then search for `System.Numerics` and add a tick-mark next the name. That should include the dll and the code should compile. – Maximilian Gerhardt Dec 08 '16 at 19:16
0

Look up for BigInteger if you're going to work with very big numbers.