Javatpoint Logo
Javatpoint Logo

Power of a Number in Java

In this section, we will write Java programs to determine the power of a number. To get the power of a number, multiply the number by its exponent.

Example:

Assume the base is 5 and the exponent is 4. To get the power of a number, multiply it by itself four times, i.e. (5 * 5 * 5 * 5 = 625).

How to Determine the Power of a Number?

  • Base and exponent should be read or initialized.
  • Take another variable power and set it to 1 to save the outcome.
  • Multiply the base by power and store the result in power using the for or while loop.
  • Repeat step 3 until the exponent equals zero.
  • Print the output.

Methods to Find the Power of a Number

There are several methods for determining a number's power:

  1. Using Java for Loop
  2. Using Java while Loop
  3. Using Recursion
  4. Using Math.pow() Method
  5. Using Bit Manipulation

1. Using Java for Loop

A for loop may be used to compute the power of a number by multiplying the base by itself repeatedly.

PowerOfNumber1.java

Output:

2 raised to the power of 3 is 8

2. Using Java while Loop

A while loop may similarly be used to achieve the same result by multiplying the base many times.

PowerOfNumber2.java

Output:

2 raised to the power of 3 is 8

3. Using Recursion:

Recursion is the process of breaking down an issue into smaller sub-problems. Here's an example of how recursion may be used to compute a number's power.

PowerOfNumber3.java

Output:

2 raised to the power of 3 is 8

4. Using Math.pow() Method

The java.lang package's Math.pow() function computes the power of an integer directly.

PowerOfNumber4.java

Output:

2.0 raised to the power of 3.0 is 8.0

Handling Negative Exponents:

When dealing with negative exponents, the idea of reciprocal powers might be useful. For instance, x^(-n) equals 1/x^n. Here's an example of dealing with negative exponents.

PowerOfNumber5.java

Output:

2.0 raised to the power of -3 is: 0.125

Optimizing for Integer Exponents:

When dealing with integer exponents, you may optimize the calculation by iterating only as many times as the exponent value. It decreases the number of unneeded multiplications.

PowerOfNumber6.java

Output:

2.0 raised to the power of 4 is: 16.0

5. Using Bit Manipulation to Calculate Binary Exponents:

Bit manipulation can be used to better improve integer exponents. To do fewer multiplications, an exponent's binary representation might be used.

PowerOfNumber7.java

Output:

2.0 raised to the power of 5 is: 32.0






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA