指数计算 m^n (可以扩展到矩阵的n次方)

来源:互联网 发布:网络无线接收器图片 编辑:程序博客网 时间:2024/06/04 18:50

原理: 

m^n= 1 (n==0)

       =(m^k) (n==2k)

      =m*m^2k (n==2k+1)

 

///////代码

//递归方式
unsigned long  recursive_power(unsigned long m, unsigned long n)
{
     unsigned long temp;

     if (n == 0)              /* m^0 = 1                  */
          return 1;
     else if (n & 0x01UL == 0) { /* if power is even then */
          temp = recursive_power(m, n >> 1);
          return temp * temp; /* m^(2k) = (m^k)^2         */
     }
     else                     /* otherwise, m^n=m*m^(n-1) */
          return m * recursive_power(m, n-1);
}


/* ------------------------------------------------------ */

#include  <stdio.h>
#include  <stdlib.h>          /* for strtoul() function   */

void main(void)
{
     char  line[100], *dummy_ptr;
     unsigned long m, n;

     printf("\nM^N Computation (M > 0 and N > 0)\n");
     printf("\nM   = ");
     gets(line);
     m = strtoul(line, &dummy_ptr, 10);
     printf("\nN   = ");
     gets(line);
     n = strtoul(line, &dummy_ptr, 10);
     printf("\n\nM^N = %lu", recursive_power(m, n));
}

 //非递归

unsigned long iterative_power(unsigned long m, unsigned long n)
{
     unsigned long  temp = 1;

     while (n > 0) {          /* if there exists 1 bits.. */
          if (n & 0x01UL == 1)/* the right most one ?     */
               temp *= m;     /* YES, the result get a 'm'*/
          m *= m;             /* anyway, compute m^k      */
          n >>= 1;            /* throw away this bit      */
     }
     return temp;
}

或:

int exponent(int m,int a){

         int ret=1;

         for (;a;a>>=1,m*=m)

                   if (a&1)

                            ret*=m;

         return ret;

}


/* ------------------------------------------------------ */

#include  <stdio.h>
#include  <stdlib.h>          /* for strtoul() function   */

void main(void)
{
     char  line[100], *dummy_ptr;
     unsigned long m, n;

     printf("\nM^N Computation (M > 0 and N > 0)\n");
     printf("\nM   = ");
     gets(line);
     m = strtoul(line, &dummy_ptr, 10);
     printf("\nN   = ");
     gets(line);
     n = strtoul(line, &dummy_ptr, 10);
     printf("\n\nM^N = %lu", iterative_power(m, n));
}

 

 

原创粉丝点击