高效求幂运算

//说明:
//高效求幂运算(递归)
//输入:整数X,幂次N
//输出:X^N
//时间复杂度:O(logN)
#include<iostream>
using namespace std;
int Pow(int X,int N)
{
    if(N==0)
        return 1;
    else if(N==1)
        return X;
    else if(N%2==0)
        return Pow(X*X,N/2);
    else
        return Pow(X*X,N/2)*X;
}
void main()
{
    cout<<"Input X and N:"<<endl;
    int X,N;
    cin>>X>>N;
    cout<<Pow(X,N)<<endl;
}

posted on 2015-06-09 19:56  Riden  阅读(162)  评论(0编辑  收藏  举报

导航