Powers of 2 can simply be computed by Bit Shift Operators

int exponent = ...
int powerOf2 = 1 << exponent;

Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring

Answer from Marco13 on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java numbers › calculating the power of any number in java without using math pow() method
Calculating the Power of Any Number in Java Without Using Math pow() Method | Baeldung
June 20, 2024 - A straightforward way to calculate the powеr of a numbеr is through itеration. Here, we’ll multiply the base by itsеlf for the specified numbеr of n times. A simple example: double result = 1; double base = 2; int exponent = 3; @Test ...
🌐
TestMu AI Community
community.testmu.ai › ask a question
How can I calculate the power of an integer in Java without using doubles? - TestMu AI Community
January 30, 2025 - I’m currently using Math.pow(a, b) to calculate powers in Java, but it returns a double, which makes my code less clean when I only need integer results. Is there a simple way to compute the power of 2 in Java (or any i…
🌐
Programiz
programiz.com › java-programming › examples › power-number
Java Program to Calculate the Power of a Number
In this program, you'll learn to calculate the power of a number with and without using pow() function.
🌐
Quora
quora.com › What-is-an-alternative-to-Math-pow-in-Java
What is an alternative to Math.pow in Java? - Quora
Answer (1 of 4): Yes you can write your function for this, [code]double power(double d, int n){ double p=1; for(int i=0;i
Top answer
1 of 6
207

You can test if a positive integer n is a power of 2 with something like

(n & (n - 1)) == 0

If n can be non-positive (i.e. negative or zero) you should use

(n > 0) && ((n & (n - 1)) == 0)

If n is truly a power of 2, then in binary it will look like:

10000000...

so n - 1 looks like

01111111...

and when we bitwise-AND them:

  10000000...
& 01111111...
  -----------
  00000000...

Now, if n isn't a power of 2, then its binary representation will have some other 1s in addition to the leading 1, which means that both n and n - 1 will have the same leading 1 bit (since subtracting 1 cannot possibly turn off this bit if there is another 1 in the binary representation somewhere). Hence the & operation cannot produce 0 if n is not a power of 2, since &ing the two leading bits of n and n - 1 will produce 1 in and of itself. This of course assumes that n is positive.

This is also explained in "Fast algorithm to check if a positive number is a power of two" on Wikipedia.


Quick sanity check:

for (int i = 1; i <= 100; i++) {
    if ((i & (i - 1)) == 0)
        System.out.println(i);
}
1
2
4
8
16
32
64
2 of 6
98

You can use the bitwise AND (&) operator:

return (num & -num) == num

Why this works?

Consider the number 8, what it is in binary (assuming 32-bits)?

0000 0000 0000 0000 0000 0000 0000 1000

Now let's see how -8 is represented? 1

1111 1111 1111 1111 1111 1111 1111 1000

Finally.. let's calculate 8 & -8:

0000 0000 0000 0000 0000 0000 0000 1000   8
↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓   &
1111 1111 1111 1111 1111 1111 1111 1000  -8
---------------------------------------
0000 0000 0000 0000 0000 0000 0000 1000   8    ¯\_(ツ)_/¯

Now let's take another example, let's say 7, which is not power of two.

0000 0000 0000 0000 0000 0000 0000 0111   7
↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓   &                       
1111 1111 1111 1111 1111 1111 1111 1001  -7
---------------------------------------
0000 0000 0000 0000 0000 0000 0000 0001  != 7  ¯\_(ة_ة)_/¯

As mentioned by @arshajii, think what will happen if num is zero.. I'll leave the solution for you :)

1 A good way to remember how to calculate that: Begin from the rightmost bit, for each 0 you see, don't change it, when you see 1, leave it and proceed, but from now on, invert all bits. I tried to explain this more here.

Find elsewhere
🌐
YouTube
youtube.com › shorts › Nq8kbckmkuE
How To Calculate Power Of A Number Without Using Math.Pow() Method in java | #java #coding - YouTube
This program tells you how to print power of a number without using math method #java#loop#forloop#coding#javacoding#javacode#code#programming#javaquestions#...
Published   April 7, 2022
🌐
w3resource
w3resource.com › java-exercises › math › java-math-exercise-16.php
Java - Power of a number without multiplication, division
import java.util.*; public class solution { public static int power(int b, int e) { if (e == 0) return 1; int result = b; int temp = b; int i, j; for (i = 1; i < e; i++) { for (j = 1; j < b; j++) { result += temp; } temp = result; } return result; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Input the base: "); int b = scan.nextInt(); System.out.print("Input the exponent: "); int e = scan.nextInt(); scan.close(); if (b>0 && e>0) System.out.println("Power of the number: "+power(b, e)); } }
Top answer
1 of 6
2

What you are asked for is to check if the number passed as an argument to the function is a power of 2, and if it is, what is the power of 2 that sums up to aNumber. (2^x = aNumber) - you want to find x.

For example if you pass 8 to the function, you should return 3, since 2^3 = 8. But if the number isn't the power of 2, you should return -1 - for example if the parameter is 9, there is no integral power of 2 that can result in 9.

Regarding your program, you can make it work with some minor modifications:

What you want to do is make a loop and in every iteration check if the input number is dividable by 2 (aNumber % 2 == 0), and if it is divide it by two (aNumber = aNumber / 2). If you can get to 1 in this way, that means that your number is a power of two, and you just have to count the iterations (number of times you divided aNumber by 2). So your function might look like this:

private static int powerOf2(int aNumber)
{
    int power = 0;
    if(aNumber % 2 != 0)
    {
        return -1;
    }
    else
    {
        System.out.print(aNumber + " is 2 raised to ");
        while (true)
        {
            if(aNumber % 2 == 0){
            aNumber /= 2;
            power++;
            if(aNumber == 1) return power;
            }else{
                return -1;
            }

        }

    }
}
2 of 6
2

Power of 2 means you can get the number by multiplying digit 2, for example:

  • If the input is 1, then you should return 0 since 20 = 1;

  • If the input is 2, then you should return 1 since 21 = 2 * 1 = 2;

  • If the input is 4, then you should return 2 since 22 = 2 * 2 = 4;

  • If the input is 8, then you should return 2 since 23 = 2 * 2 * 2 = 8;

...

If the input is 0 or negative, you should return -1;

If the input is not a power of 2(for example 3, 5, 7, 10), you should return -1;

🌐
Spiceworks
community.spiceworks.com › programming & development
Math.pow() Method Not Operating Correctly? - Programming & Development - Spiceworks Community
July 14, 2015 - I’m new to Java. I am working with the Math.pow(); method, and I am not sure exactly what it is doing. For example, if I declare an integer called power that is equal to 2, then I use Math.pow(); to raise it by 2, to the power of 2. When I then print it, I still get 2. That definitely does ...
🌐
Reddit
reddit.com › r/learnprogramming › [java] calculate x^n without math.pow(x,n) and with an array?
r/learnprogramming on Reddit: [Java] Calculate X^n without Math.pow(x,n) and with an array?
January 7, 2017 -

I've been trying to calculate the Xn without using math.pow in order to compare it with other algorithms to test their performance and math.pow is too optimized so it will impede me to compare it successfully with other algorithms:

I will use the Xn method to use it within a bruteforce method that evaluates a polynomial at x.

This method will be compared with my horners method.

If I do it using math.pow(x,n) the bruteforce will be faster than horners sometimes and I presume that its because math.pow being too fast.

Here are both method to compare, can you shed some light on why sometimes bruteforce is faster than horners, is it because of math.pow?

    //Metodo de Horner:
 public double horners(int[] coef_array, double x) {
    double resultado = 0;
    int c = 0;
    for (int i = coef_array.length - 1; i >= 0; i--) {
        resultado = (resultado * x) + coef_array[i];
        c++;
    } //Evalua en x; 
    set_cant_mult_H(c);
    return resultado;
}

//Metodo "obvio", "a pie" o "bruteforceado":
public double brute(int[] coef_array, double x) {
    double resultado = 0;
    int c = 0;
    for (int i = coef_array.length - 1; i >= 0; i--) {
        c++;
        resultado += coef_array[i] * Math.pow(x, i); // Change this mathpow with something slower?!
    }
    set_cant_mult_BF(c);
    return resultado;
}    

So to wrap it off, Horners bruteforce are compared but sometimes horners is slower than bruteforce and I presume its because math.pow(x,n) is too fast.

Remember I am using arrays so maybe the new pow method may need to receive an array!

🌐
Sololearn
sololearn.com › en › Discuss › 125234 › how-can-i-code-a-formula-with-power-without-using-math-pow
How can i code a formula with power without using math.pow? | Sololearn: Learn to code for FREE!
java · 11th Dec 2016, 2:06 PM · mark daquis · 2 Answers · Answer · + 6 · public static int power(int base, int exponent) { int result = base; for (int x = 1; x < exponent; ++x) { result *= base; } return result; } 11th Dec 2016, 2:17 PM · Kerrash · 0 ·
🌐
LeetCode
leetcode.com › problems › power-of-two
Power of Two - LeetCode
Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2x. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: ...
🌐
Educative
educative.io › answers › how-to-use-the-mathpow-method-in-java
How to use the Math.pow() method in Java
The power of a number refers to how many times to multiply the number with itself. ... The method takes the base and exponent parameters of type double. The method calculates multiplication of the base with itself exponent times and returns the result of type double. ... The pow() method is a part of java.lang.Math class, you need to import this class in your code to use the function.