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(); } }