最近复习数据结构,弱弱的写了写练习,这个是计算任意整数的任意次幂的算法
[color=blue]/*
* Author: Kevin Alps
* Date: 2010-09-12
* Function:计算任意整数的任意幂
*/[/color]
[color=green]#include <iostream>
#include <math.h>[/color]
[color=green]#define MAXSIZE 100[/color]
[color=yellow]using namespace std;[/color]
[color=blue]/*
* Parameter:
* result:结果数组 n:底数 exponent:指数 maxsize:结果数组的位数
*/[/color]
[color=red]void mypow(int *result, int n, int exponent, int maxsize)
{
//计算,每一位和底数相乘,然后进行进位处理,重复exponent次
for(int k=0; k<exponent; k++)
{
for(int i=0; i<maxsize; i++)
{
result[i] *= n;
}
for(int i=0; i<maxsize; i++)
{
if(result[i] > 9)
{
result[i+1] = result[i]/10+result[i+1];
result[i] = result[i] % 10;
}
}
}
}
int main()
{
int n; //底数
int exponent; //指数
cout << "Please input the number: ";
cin >> n;
cout << "Please input the exponent: ";
cin >> exponent;
int result[MAXSIZE]; //结果数组,结果在100位数以内,再大的话可以修改
for(int i=0; i<MAXSIZE; i++) result[i]=0; //初始化结果数组
result[0] = 1; //从零次方开始
mypow(result, n, exponent, MAXSIZE);
//打印出结果
cout << "The result of " << n << "**" << exponent << " is: ";
for(int i=MAXSIZE-1; i>-1; i--)
{
cout << result[i] << " ";
}
return 0;
}[/color]
[color=blue]/*
* Author: Kevin Alps
* Date: 2010-09-12
* Function:计算任意整数的任意幂
*/[/color]
[color=green]#include <iostream>
#include <math.h>[/color]
[color=green]#define MAXSIZE 100[/color]
[color=yellow]using namespace std;[/color]
[color=blue]/*
* Parameter:
* result:结果数组 n:底数 exponent:指数 maxsize:结果数组的位数
*/[/color]
[color=red]void mypow(int *result, int n, int exponent, int maxsize)
{
//计算,每一位和底数相乘,然后进行进位处理,重复exponent次
for(int k=0; k<exponent; k++)
{
for(int i=0; i<maxsize; i++)
{
result[i] *= n;
}
for(int i=0; i<maxsize; i++)
{
if(result[i] > 9)
{
result[i+1] = result[i]/10+result[i+1];
result[i] = result[i] % 10;
}
}
}
}
int main()
{
int n; //底数
int exponent; //指数
cout << "Please input the number: ";
cin >> n;
cout << "Please input the exponent: ";
cin >> exponent;
int result[MAXSIZE]; //结果数组,结果在100位数以内,再大的话可以修改
for(int i=0; i<MAXSIZE; i++) result[i]=0; //初始化结果数组
result[0] = 1; //从零次方开始
mypow(result, n, exponent, MAXSIZE);
//打印出结果
cout << "The result of " << n << "**" << exponent << " is: ";
for(int i=MAXSIZE-1; i>-1; i--)
{
cout << result[i] << " ";
}
return 0;
}[/color]