求x的n次幂,并返回计算结果
int qpow(int x, int k)
{
int ret = 1;
while(k)
{
if(k & 1)
ret = ret * x;
x = x * x, k >>= 1;
}
return ret;
}
我用的是 快速幂
, 时间复杂度 O(log k)
,相对于别的 O(k)
算法 时间复杂度算是十分优秀的了
你这个依照题目来的话,目前你只缺少定义power函数,需要在main函数外定义一个power函数,既然你在深究这个题目那就认为你学过函数的定义和调用了
#include<stdio.h>
{
{
int power(int a,int b);
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",power(a,b));
}
}
int power(int a,int b)
{
int t=1,i;
if(b==0)
{
return 1;
}
else
{
for(i=1;i<=b;i++)
{
t=a*t;
}
return t;
}
}
因为题目规定了是int型函数,就定义int power(int a,int b)然后分为0和非零的情况讨论
(其实有一个函数是pow(a,b)本来就是计算a的b次方的,只要在开头添加一个#include<math.h>即可)
int power(int a,int b){
return pow(a,b);
}
#include <stdio.h>
#include <math.h>
int main()
{
double s;
int a,b,x;
scanf("%d%d",&a,&b);
s = pow(a,b);
x = s;
printf("%d\n",x);
return 0;
}