Is there has a function Math.Pow(A,n) for long type?

半城伤御伤魂 提交于 2020-07-03 10:19:13

问题


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!


回答1:


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




回答2:


    public static ulong Power(ulong A, ulong n)
    {
        ulong result = n;
        for(ulong i = 0; i < A; i++)
        {
            result *= A;
        }
        return result;
    }

    static void Sample()
    {
        Console.WriteLine("Result: " + Power(12, 62));
    }

Output Result: 552798227791872




回答3:


  public static long Power(long A, ulong n)
    {
        long result = 1;    // if n==0,A^n==1

        if (n>0)
        {
            do
            {
                result *= A;
                n--;
            } while (n>0);
        }            
        return result;
    }


来源:https://stackoverflow.com/questions/39181444/is-there-has-a-function-math-powa-n-for-long-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!