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
🌐
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
February 2, 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…
🌐
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 ...
🌐
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 ...
Top answer
1 of 3
4

First, observe that pow(a,x) = exp(x * log(a)).

You can implement your own exp() function using the Taylor series expansion for ex:

ex = 1 + x + x2/2! + x3/3! + x4/4! + x5/5! + ...

This will work for non-integer values of x. The more terms you include, the more accurate the result will be.

Note that by using some algebraic identities, you only need to resort to the series expansion for x in the range 0 < x < 1 . exp(int + frac) = exp(int)*exp(frac), and there's no need to use a series expansion for exp(int). (You just multiply it out, since it's an integer power of e=2.71828...).

Similarly, you can implement log(x) using one of these series expansions:

log(1+x) = x - x2/2 + x3/3 - x4/4 + ...

or

log(1-x) = -1 * (x + x2/2 + x3/3 + x4/4 + ... )

But these series only converge for x in the interval -1 < x < 1. So for values of a outside this range, you might have to use the identity

log(pq) = log(p) + log(q)

and do some repeated divisions by e (= 2.71828...) to bring a down into a range where the series expansion converges. For example, if a=4, you'd have to take take x=3 to use the first formula, but 3 is outside the range of convergence. So we start dividing out factors of e:

4/e = 1.47151...

log(4) = log(e*1.47151...) = 1 + log(1.47151...)

Now we can take x=.47151..., which is within the range of convergence, and evaluate log(1+x) using the series expansion.

2 of 3
0

Think about what a power function should do.

Mathematically: x^5 = x * x * x * x * x, or ((((x*x)*x)*x)*x)

Within your for loop, you can use the *= operator to achieve the operation that happens above.

How are you handling fractions? Java has no built-in fraction type; it stores decimals that would calculate the same way as integers (in other words, x * x works with both types). If you have a special class for fractions, your loop just needs two steps: one to multiply the numerator and one to multiply the denominator.

🌐
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 10, 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: ...