Download as docx
Download as docx
You are on page 1of 1

Power :

Xn
public class Exponenta {
public static double powerLoop( double x , int n ){
double evenPower = x;
double result;
if (n%2 != 0 ){
result = x;
}
else{
result = 1;
}
n = n/2;
while ( n != 0 ){
evenPower = evenPower*evenPower;
if ( (n % 2) != 0 ){
result = result*evenPower;
}
n = n/2;
} // end while
return result;
} // end power

public static double powerRecursion(double x, int n){


if ( n == 0){
return 1;
}
else if (n%2 == 0){
return powerRecursion(x*x, n/2);
}
else{
return x*powerRecursion(x*x, (n - 1)/2);
}
}

public static void main(String[] args) {


// loop
for(int i=1; i<=10; i++){
System.out.print(powerLoop(2, i)+", ");
}
System.out.println();
// recursion
System.out.println("\n\nrecurs\n");
for(int i=1; i<=10; i++){
System.out.print(powerRecursion(2, i)+", ");
}
System.out.println();
}

You might also like