Java program to find the power of any number x^y
ADVERTISEMENTS
Java program to find the power of any number x^y. There are you will learn how to find the power of any number x^y in the Java language.
Formula:
r = b ^ y
where:
r = result
b = base value
y = exponent value
There are two ways to implement these formulae:
- By using the default method
- Second, by using Math.pow() function
1. By using the default method
// Java program to find the power of any number
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the base & exponent values::\n");
int b = in.nextInt();
int e = in.nextInt();
int r = 1;
int i = 1;
// b = base
// e = exponent
// r = result
/* finding power of base value by equiping exponent value */
while(i <= e) {
r *= b;
i++;
}
// Output
System.out.println("\nResult:: " + b + "^" + e + " = " + r + "\n");
}
}
Output:
Enter the base & exponent values::
5
7
Result:: 5^7 = 78125
2. By using Math.pow() function
// Java program to find the power of any number by using Math.pow() function
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the base & exponent values::\n");
int b = in.nextInt();
int e = in.nextInt();
int r = 1;
// b = base
// e = exponent
// r = result
/* finding power of base value by equiping exponent value */
r = (int)Math.pow(b, e);
// Output
System.out.println("\nResult:: " + b + "^" + e + " = " + r + "\n");
}
}
Output:
Enter the base & exponent values::
5
7
Result:: 5^7 = 78125