Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2501239
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2011-05-20 09:28:22

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

  2. unsigned long myPow(int m, int n)
  3. {
  4.   unsigned long tmp;
  5.   if(n == 0)
  6.     return 1;
  7.   if(n == 1)
  8.     return m;
  9.   if(n % 2 == 0){
  10.     tmp = myPow(m, n/2);
  11.     return tmp*tmp;
  12.   }
  13.   else{
  14.     return m*myPow(m, n-1);
  15.   }
  16. }

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

  25.   return 0;
  26. }
程序执行结果如下:
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
阅读(5899) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~