#include <stdio.h>
#include <math.h>
//递归算法
int recursion(int a,int b)
{
int tem = 1;
if(b==0)return 1;
else if(b==1)return a;
tem = recursion(a,b>>1);
tem = tem*tem;
if(b&1) tem = tem * a;
return tem;
}
//循环算法
int loop(int a,int b)
{
int tem=1,ret=a;
while(b>0)
{
if(b&1) tem = tem * ret;
ret = ret*ret;
b>>=1;
}
return tem;
}
int main()
{
int a,b;
while(1)
{
printf("For a^b input a and b:");
scanf("%d%d",&a,&b);
printf("The recursion method:\n");
printf("%d\n",recursion(a,b));
printf("The loop method:\n");
printf("%d\n",loop(a,b));
}
return 0;
}
#include <math.h>
//递归算法
int recursion(int a,int b)
{
int tem = 1;
if(b==0)return 1;
else if(b==1)return a;
tem = recursion(a,b>>1);
tem = tem*tem;
if(b&1) tem = tem * a;
return tem;
}
//循环算法
int loop(int a,int b)
{
int tem=1,ret=a;
while(b>0)
{
if(b&1) tem = tem * ret;
ret = ret*ret;
b>>=1;
}
return tem;
}
int main()
{
int a,b;
while(1)
{
printf("For a^b input a and b:");
scanf("%d%d",&a,&b);
printf("The recursion method:\n");
printf("%d\n",recursion(a,b));
printf("The loop method:\n");
printf("%d\n",loop(a,b));
}
return 0;
}