5

I'm testing a small C# program fragment:

        short min_short = (short)(int)-Math.Pow(2,15);   
        short max_short = (short)(int)(Math.Pow(2, 15) - 1);
        Console.WriteLine("The min of short is:{0};\tThe max of short is:{1}", min_short, max_short);

        int min_int = (int)-Math.Pow(2, 31);
        int max_int = (int)(Math.Pow(2, 31) - 1);
        Console.WriteLine("The min of int is:{0};\tThe max of int is:{1}", min_int, max_int);

        uint min_uint = 0;
        uint max_uint = (uint)(Math.Pow(2, 32) - 1);
        Console.WriteLine("The min of uint is:{0};\tThe max of uint is:{1}", min_uint, max_uint);

        long min_long = (long)-Math.Pow(2, 63);
        long max_long = (long)(Math.Pow(2, 63) - 1);
        Console.WriteLine("The min of long is:{0};\tThe max of long is:{1}", min_long, max_long);

        ulong min_ulong = 0;
        ulong max_ulong = (ulong)(Math.Pow(2, 64) - 1);
        Console.WriteLine("The min of ulong is:{0};\tThe max of ulong is:{1}", min_ulong, max_ulong);

The output is:

The min of ushort is:0; The max of ushort is:65535
The min of short is:-32768;     The max of short is:32767
The min of int is:-2147483648;  The max of int is:2147483647
The min of uint is:0;   The max of uint is:4294967295
The min of long is:-9223372036854775808;The max of long is:-9223372036854775808
The min of ulong is:0;  The max of ulong is:0

I suspect that the mistake is caused by the function of Math.Pow(),which is double type returned.

public static double Pow(
    double x,
    double y
)

so,my question is: Is there has a similar Math function for long type? How to correct the errors in the program fragment above. Many thanks!

Wuying283
  • 99
  • 1
  • 6
  • Possible duplicate of [C# memory type bigger than ulong](http://stackoverflow.com/questions/7968540/c-sharp-memory-type-bigger-than-ulong) – Gabriel GM Aug 27 '16 at 13:11

1 Answers1

9

You reached Math.Pow limit. You would need to use System.Numerics.BigInteger.Pow.

Gabriel GM
  • 6,391
  • 2
  • 31
  • 34
  • Thanks a lot.A few minutes ago, I used a stupid method - a custom function Power – Wuying283 Aug 27 '16 at 13:36
  • 1
    But how do you use it? It just returns a `System.Numerics.BigInteger` instead of a `long`, `ulong` or any of the other desired types. – Matt Arnold Apr 23 '19 at 09:20
  • 1
    Not sure of your question, but `BigInteger` is a `struct` which is used to store the number just like a `long`, but bigger. So you can do whatever you want with it. – Gabriel GM Apr 27 '19 at 00:18