指数计算 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));
}
- 指数计算 m^n (可以扩展到矩阵的n次方)
- 计算M的N次方
- 计算n的m次方算法
- 快速计算n的m次方
- 计算 任意大N的M次方
- n的m次方的计算(Exponentiation)
- m的n次方
- 计算N的M次方的最后3位数
- n的m次方 bjfu1056
- bjfu1056 N的M次方
- 求m的n次方
- M*N的矩阵
- C/C++ 编程计算2的100万次方(m的n次方),超长结果输出文件
- 计算x的n次方
- 计算x的n次方
- 计算2的n次方
- 计算2的N次方
- 计算3的n次方(n到能到200多)
- 多用户openvpn的架设与配置
- __declspec(dllimport)
- How to code the forward declaration of class or struct using template?
- platform_device
- javascript操作class属性
- 指数计算 m^n (可以扩展到矩阵的n次方)
- MPI编程中并行前缀和计算
- t1
- Python 图片拼接
- javascript的innerHTML
- 加减乘除运算
- 关于char*与char[]的区别
- linux设备模型之platform总线
- 父窗口和窗口拥有者的区别