0% found this document useful (0 votes)
46 views

Power:: Public Class Public Static Double Double Int Double Double If

This Java class contains two methods to calculate exponential powers - powerLoop uses a looping approach, while powerRecursion uses recursion. The main method tests both by calculating 2^n for n from 1 to 10 and printing the results.

Uploaded by

igorvilst7184
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX or read online on Scribd
0% found this document useful (0 votes)
46 views

Power:: Public Class Public Static Double Double Int Double Double If

This Java class contains two methods to calculate exponential powers - powerLoop uses a looping approach, while powerRecursion uses recursion. The main method tests both by calculating 2^n for n from 1 to 10 and printing the results.

Uploaded by

igorvilst7184
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX or read online on Scribd
You are on page 1/ 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