# 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: an improved method to evaluate the Y Power of integer x * language: C ++ * Development Environment: vc6.0 * Author: wangzhicheng * E-mail: 2363702560@qq.com * Date: 2012/10/14 * // * The core method is to use the property of the square when X is obtained, x ^ 2 = x * X, when x ^ 2 is obtained, x ^ 4 = (x ^ 2) * (x ^ 2), and so on */const int max = 100000000; // class power {privat E: int base; // base number int exponent; // index long result; // storage result public: Power (int B, int e) {If (B <0 | B> = max) {cerr <"the base number should be greater than or equal to 0 and less than" <max <Endl; exit (1 );} if (E <0 | E> MAX/10000) {cerr <"index should be greater than or equal to 0 and less than" <(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 ;} setresu LT (result); show () ;}void show () {If (result <0) {cerr <"result overflow! "<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; // The first nominal value int temp = base; // the corresponding weight of each bit 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 (x, y); power. power (); power. power_common ();}}