Hi Stack overflow community recently came across this question.. where the interviewer asked me to find the power of the given number without any loop or recursive call no inbuilt.
Example :2^3 = 8 , 3 ^ 3 = 27
please let me know if there is a ans :)
My approach was
int val = 2;
int pow = 3;
while (pow != 0)
{
result *= val;
--pow;
}
CodePudding user response:
The cleanest way is using package java.lang.Math
Always remember:
"If already exist, don't create it"
double val = 2;
double pow = 3;
System.out.println(Math.pow(val, pow));
Math have some many other uses, like Pi number, trigonometry, random numbers... Check it out here
CodePudding user response:
You can use recursive method. An example code is:
public static void main(String[] args) {
System.out.println(power(3,3));
System.out.println(power(2,3));
}
public static int power(int value, int pow){
if(pow > 1){
return value * power(value, pow - 1);
}
return value;
}