计算X的n次幂,有多种算法
    例子:计算2的62次方。
    method 1 :time = 2099 纳秒。
    image.png
    常规思路,进行61次的乘法!

    1. Stopwatch sw = new Stopwatch();
    2. Console.WriteLine($"{sw.Elapsed} start");
    3. sw.Start();
    4. Console.WriteLine(Math.Pow(2,62));
    5. sw.Stop();

    method 2 :time = 113 纳秒
    进行拆分:2^62 = (2^31)^2 = (2^31)(2^31) // 得到 2^31 的值的情况下,需要 1 次乘法
         2^31 = (2^15)^2
    2 = (2^15)(2^15)2 // 得到 2^15 的值的情况下,需要 2 次乘法
         2^15 = (2^7)^22 = (2^7)(2^7)2 // 得到 2^7 的值的情况下,需要 2 次乘法
         2^7 = (2^3)^2
    2 = (2^3)(2^3)2 // 得到2^3 的值的情况下,需要 2 次乘法 
         2^3 = 222            // …………………………,需要2次乘法
    所以:该方法需 2+2+2+2+1 = 9 次乘法!

    1. class Program
    2. {
    3. static void Main(string[] args)
    4. {
    5. Stopwatch sw = new Stopwatch();
    6. Console.WriteLine($"{sw.Elapsed} start");
    7. sw.Start();
    8. Console.WriteLine(Math.Pow(2,1000));
    9. sw.Stop();
    10. Console.WriteLine($"{sw.Elapsed} end");
    11. sw.Restart();
    12. pow(2, 1000);
    13. Console.WriteLine(sw.Elapsed);
    14. Console.ReadKey();
    15. }
    16. public static long pow(long x, long n)
    17. {
    18. if (n == 0)
    19. {
    20. return 1;
    21. }
    22. // 如果是偶数
    23. if (isEven(n))
    24. {
    25. return pow(x * x, n / 2);
    26. }
    27. else
    28. {
    29. return pow(x * x, n / 2) * x;
    30. }
    31. }
    32. private static Boolean isEven(long x)
    33. {
    34. if (x % 2 == 0)
    35. {
    36. return true;
    37. }
    38. if (x % 2 == 1)
    39. {
    40. return false;
    41. }
    42. return false;
    43. }
    44. }