计算任意整数的任意幂

最近复习数据结构,弱弱的写了写练习,这个是计算任意整数的任意次幂的算法

[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]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值