一种改进的求整数x的y次幂
发布时间:2020-12-16 07:43:35 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #include iostream#include cstdlib#include ctimeusing namespace std; /*This is a free Program,You can modify or redistribute it under the ter
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 #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: [email?protected] *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(); } } 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |