分治法~乘方问题优化

#include<iostream>
using namespace std;

int power(int x, int n)
{//分治法,时间复杂度:lgn
    if(x == 0)
    {
        if(n == 0)
            cout << "WRONG INPUT: SIGNIGICANT!!!" << endl;
        return 0;
    }
    if(n == 0)
        return 1;
    int sum = 1;
    int t = power(x, n/2);
    sum = t*t;
    if(n % 2)
        sum *= x;
    return sum;
}

int main()
{
    int x, n;
    while(cin >> x >> n, n != 0 || x != 0)
    {
        cout << x << " to the " << n << " is : " << power(x, n) << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/sanghai/p/2809977.html