编写程序实现计算x的n次幂
采用两种算法
朴素算法:x*x*x......
分治算法:
n为偶数:x的n/2次幂*x的n/2次幂
n为奇数:x的(n-1)/2次幂*x的(n-1)/2次幂
代码
#include<bits/stdc++.h>
using namespace std;
//朴素算法
int pusu(int x,int n)
{
int num=1;
for(int i=0;i<n;i++)
{
num*=x;
}
return num;
}
//分治算法----快速幂
int fenzhi(int x,int n)
{
int num=1;
while(n)
{
if(n%2==1)
{
num*=x;
n--;
}
x*=x;
n/=2;
}
return num;
}
int main()
{
int x,n;
cin>>x>>n;
int result;
clock_t start_time=clock();
{
result=pusu(x,n);
}
clock_t end_time=clock();
cout<<"朴素算法结果:"<<result<<endl;
printf("Running time is: %lfms\n",static_cast<double>(end_time-start_time)/CLOCKS_PER_SEC*1000);
clock_t start_time1=clock();
{
result=fenzhi(x,n);
}
clock_t end_time1=clock();
cout<<"分治算法结果:"<<result<<endl;
printf("Running time is: %lfms\n",static_cast<double>(end_time1-start_time1)/CLOCKS_PER_SEC*1000);
return 0;
}
测试数据