TaGi Asadullazadeh
TaGi Asadullazadeh

Reputation: 91

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?

Upvotes: 3

Views: 3050

Answers (2)

Maximilian Gerhardt
Maximilian Gerhardt

Reputation: 5353

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.

Upvotes: 9

user6516640
user6516640

Reputation: 13

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

Upvotes: 0

Related Questions