首页 > 其他 > 详细

二分计算x的n次方

时间:2014-03-18 12:21:21      阅读:283      评论:0      收藏:0      [点我收藏+]

计算x的n次方。要求时间控制在log2n内。

bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            const int n = 10;
            for (int i = 1; i <= 5; ++i)
            {
                int a = exp(i, n);
                int b = binexp(i, n);
                Console.WriteLine(string.Format("Calc {0}, Value: {1}={2}, TestResult: {3}",
                    i, 
                    a, b,
                    a == b
                    ));
            }
        }

        static int exp(int a, int n)
        {
            if (n == 0) return 1;

            return a * exp(a, n - 1);
        }

        static int binexp(int a, int n)
        {
            if (n == 0) return 1;

            else if (n % 2 == 0)
            {
                int b = binexp(a, n / 2);
                return b * b;
            }

            return a * binexp(a, n - 1);
        }
    }
}
bubuko.com,布布扣

二分计算x的n次方,布布扣,bubuko.com

二分计算x的n次方

原文:http://www.cnblogs.com/liquadli/p/3604803.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!