• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

c语言一种改进的pow(x,y)

OC/C/C++ 水墨上仙 1526次浏览

c语言一种改进的pow(x,y)
来源:http://blog.csdn.net/wangzhicheng2013/article/details/8069524

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
/*
This is a free Program, You can modify or redistribute it under the terms of GNU
*Description:一种改进的求整数x的y次幂
*Language: C++
*Development Environment: VC6.0
*Author: Wangzhicheng
*E-mail: 2363702560@qq.com
*Date: 2012/10/14
*/
/*
核心方法是利用乘方的性质
当x求出,x^2=x*x,当x^2求出,x^4=(x^2)*(x^2) ,依次类推
*/
const int max=100000000;  //底数最大的数
class Power {
private:
	int base;       //底数
	int exponent;    //指数
	long result;    //存放结果
public:
	Power(int b,int e) {
		if(b<0 || b>=max) {
			cerr<<"底数应该大于等于0且小于"<<max<<endl;
			exit(1);
		}
		if(e<0 || e>max/10000) {
			cerr<<"指数应该大于等于0且小于"<<(max/10000)<<endl;
			exit(1);
		}
		base=b;
		exponent=e;
	}
	void power() {
		int result=1;
		power(exponent,result);
		setResult(result);
		show();
	}
	void power_common() {
		int i;
		int result=1;
		for(i=0;i<exponent;i++) {
			result=result*base;
		}
		setResult(result);
		show();
	}
	void show() {
		if(result<0) {
			cerr<<"结果溢出!"<<endl;
			result=0;
			return;
		}
		cout<<"power("<<base<<","<<exponent<<")="<<result<<endl;
	}
private:
	void setResult(int r) {
		result=r;
	}
	void power(int exponent,int &result) {
		int pre=1;     //前面值
		int temp=base;    //每一位对应的权值
		while(exponent) {
			if(exponent%2) {
				result=pre*temp;
				pre=result;
			}
			temp=temp*temp;
			exponent/=2;
		}
	}
};
void main() {
	srand(unsigned(time(0)));
	int i;
	int x,y;
	const int N=10;
	for(i=0;i<N;i++) {
		x=rand()%(N*N);
		y=rand()%N;
		Power power(x,y);
		power.power();
		power.power_common();
	}
}


喜欢 (0)
加载中……