计算x的n次方。要求时间控制在log2n内。
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); } }}