一種改進的求整數x的y次冪

jopen 9年前發布 | 8K 次閱讀 C/C++

#include <iostream>

include <cstdlib>

include <ctime>

using namespace std;

/ This is a free Program, You can modify or redistribute it under the terms of GNUDescription:一種改進的求整數x的y次冪 Language: C++Development Environment: VC6.0 Author: WangzhichengE-mail: 2363702560@qq.com Date: 2012/10/14/

/ 核心方法是利用乘方的性質 當x求出,x^2=xx,當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=resultbase; } 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=pretemp; 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(); } }</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!