- 1

code for solve power with out use Math class

28th Nov 2016, 5:54 PM
masih
2 Answers
0
// (not really optimized way:) int myNum = 5; int pow = 2; int base = myNum; for (int i = 1; i < pow: i++) myNum *= base; //As method: public int pow(int num, int pow) { int base = num; for (int i = 1; i < pow; i++) num *= base; return num; } int i25 = pow(5, 2); //You can replace the int type to float, double, what you want. A bit of optimalization: public int pow(int base, int pow) { while (pow % 2 == 0) { base *= base; pow /= 2; } int num = base; for (int i = 1; i < pow; i++) num *= base; return num; }
28th Nov 2016, 6:16 PM
Magyar DĂĄvid
Magyar DĂĄvid - avatar
0
I wonder what would be the reason to reinvent the wheel? since this solution does not cover any exceptions like x^0 always equals 1, x^1 always equals x, x^-1 always equals 1/x and so on...
28th Nov 2016, 7:26 PM
ordens
ordens - avatar