1

Math.Pow seems to be not working correctly for big results. Probably that is because it uses double for calculations (How is Math.Pow() implemented in .NET Framework?).

For example:

public static void Main()
{
    Console.WriteLine((long)Math.Pow(17, 13));
    Console.WriteLine(Pow(17, 13));
}

public static long Pow(int num, int pow)
{
    long answer = 1;
    for (int i = 0; i < pow; i++)
    {
        answer *= num;
    }

    return answer;
}

The result from the above code is:

9904578032905936
9904578032905937

Are there any built-in .NET alternatives for using power of a number without errors?

Community
  • 1
  • 1
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123

1 Answers1

10

The BigInteger structure has a Pow method. This structure resides in the System.Numerics namespace, and was introduced in .NET Framework 4.0. You need to add a reference to the System.Numerics assembly before using it.

using System;
using System.Numerics;

public static class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine(BigInteger.Pow(17, 13));   // 9904578032905937
    }
}

Note that BigInteger is only suitable for integer arithmetic; it cannot handle fractional numbers.

Douglas
  • 53,759
  • 13
  • 140
  • 188