递归法求幂

    编写一个递归算法,求解m的n次方。
    我们一般求解m的n次方,一般使用n个m相乘的办法来求解。其实我们还可以使用另外一种更有效率的办法求解这个问题。我们知道一个数的0次方等于1,一个数的1次方等于该数本身。如果一个数的n次方的n可以被2整数,我们可以将求解的问题,分解为m的(n/2)次方乘以m的(n/2)次方。如果不能被2整除,则可以将问题求解转变为m乘以m的(n-1)次方,通过这个递归的办法,我们可以很快的分解求出问题。编写代码如下:
#include <stdio.h>

unsigned long myPow(int m, int n)
{
  unsigned long tmp;
  if(n == 0)
    return 1;
  if(n == 1)
    return m;
  if(n % 2 == 0){
    tmp = myPow(m, n/2);
    return tmp*tmp;
  }
  else{
    return m*myPow(m, n-1);
  }
}

int main(int argc, char *argv[])
{
  int m,n;
  printf("please input the bottom number.\n");
  scanf("%d", &m);
  printf("please input the exponent number.\n");
  scanf("%d", &n);
  printf("the result of power(%d,%d) is %ld\n", m, n, myPow(m, n));

  return 0;
}
程序执行结果如下:
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ gcc 6.14.c
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out
please input the bottom number.
5
please input the exponent number.
5
the result of power(5,5) is 3125

猜你喜欢

转载自775121986.iteye.com/blog/1837723