6

This is my program

// ************************************************************
    // PowersOf2.java
    //
    // Print out as many powers of 2 as the user requests
    //
    // ************************************************************

    import java.util.Scanner;

    public class PowersOf2 {

    public static void main(String[] args)

    {
        int numPowersOf2; //How many powers of 2 to compute
        int nextPowerOf2 = 1; //Current power of 2
        int exponent= 1;
        double x;

         //Exponent for current power of 2 -- this
        //also serves as a counter for the loop Scanner

        Scanner scan = new Scanner(System.in);
        System.out.println("How many powers of 2 would you like printed?");
        numPowersOf2 = scan.nextInt();
        System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
        //initialize exponent -- the first thing printed is 2 to the what?

    while( exponent <= numPowersOf2)
        {
        double x1 = Math.pow(2, exponent);
        System.out.println("2^" + exponent + " = " + x1);
                exponent++;
        }   
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent

    }
}

The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.

tutak
  • 1,120
  • 1
  • 15
  • 28
user3552056
  • 61
  • 1
  • 1
  • 2

12 Answers12

15

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

Marco13
  • 53,703
  • 9
  • 80
  • 159
1

If there are no performance constraints you can do:

double x1=1;

for(int i=1;i<=numPowersOf2;i++){
   x1 =* 2
}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
tutak
  • 1,120
  • 1
  • 15
  • 28
1

Here is a post that allows both negative/positive power calculations.

https://stackoverflow.com/a/23003962/3538289

Function to handle +/- exponents with O(log(n)) complexity.

double power(double x, int n){
 if(n==0)
  return 1;

  if(n<0){
      x = 1.0/x;
      n = -n;
  }
 double ret = power(x,n/2);
 ret = ret * ret;
 if(n%2!=0)
   ret = ret * x;
 return ret;
}
Community
  • 1
  • 1
cevaris
  • 5,671
  • 2
  • 49
  • 34
1

You could implement your own power function.

The complexity of the power function depends on your requirements and constraints. For example, you may constraint exponents to be only positive integer.

Here's an example of power function:

public static double power(double base, int exponent) {
    double ans = 1;
    if (exponent != 0) {
        int absExponent = exponent > 0 ? exponent : (-1) * exponent;
        for (int i = 1; i <= absExponent; i++) {
            ans *= base;
        }

        if (exponent < 0) {
            // For negative exponent, must invert
            ans = 1.0 / ans;
        }
    } else {
        // exponent is 0
        ans = 1;
    }

    return ans;
}
wns349
  • 1,266
  • 1
  • 10
  • 20
1

You can try to do this based on this explanation:

 public double myPow(double x, int n) {

    if(n < 0) {
        if(n == Integer.MIN_VALUE) {
            n = (n+1)*(-1);
            return 1.0/(myPow(x*x, n));
        }
        n = n*(-1);
        return (double)1.0/myPow(x, n);
    }
    double y = 1;
    while(n > 0) {
        if(n%2 == 0) {
           x = x*x; 
        }
        else {
            y = y*x;
            x = x*x;
        }
         n = n/2;
    }
    return y;   
}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.

xy = ey∙ln(x)

In Java this would look like

public static double myPow(double x, double y){
  return Math.exp(y*Math.log(x));
}

If you really need a loop, you can use something like the following

public static double myPow(double b, int e) {
  if (e < 0) {
    b = 1 / b;
    e = -e;
  }

  double pow = 1.0;
  double intermediate = b;
  boolean fin = false;

  while (e != 0) {
    if (e % 2 == 0) {
      intermediate *= intermediate;
      fin = true;
    } else {
      pow *= intermediate;
      intermediate = b;
      fin = false;
    }
    e >>= 1;
  }

  return pow * (fin ? intermediate : 1.0);
}
andand
  • 17,134
  • 11
  • 53
  • 79
0
// Set the variables

int numPowersOf2;        //How many powers of 2 to compute
int nextPowerOf2 = 1;    //Current power of  2
int exponent = 0;  


/* User input here */

// Loop and print results

do
   {

    System.out.println ("2^" + exponent + " = " + nextPowerOf2);

    nextPowerOf2 = nextPowerOf2*2;

    exponent ++;
  } 
while (exponent < numPowersOf2);
Pang
  • 9,564
  • 146
  • 81
  • 122
0

here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)

    String base ="";
    String exp ="";
    BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
    try {System.out.print("enter the base number: ");
        base = value.readLine();
        System.out.print("enter the exponent: ");
        exp = value.readLine(); }
    catch(IOException e){System.out.print("error");}

    int x = Integer.valueOf(base);
    int n = Integer.valueOf(exp);
    int y=x;
    int m=1;       
    while(m<n+1) {
        System.out.println(x+"^"+m+"= "+y);
        y=y*x;
        m++;    
    }
AVos
  • 1
0

To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.

static float power(float a, int b)
{
    float temp;
    if( b == 0)
        return 1;
    temp = power(a, b/2); 

    // if even times
    if (b%2 == 0)
        return temp*temp;
    else  // if odd times
    {
        if(b > 0)
            return a * temp * temp;
        else  // if negetive i.e. 3 ^ (-2)
            return (temp * temp) / a;
    }
} 
mpatel
  • 348
  • 2
  • 13
0

I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.

public class trythis {
    public static void main(String[] args) {
        int b = 2;
        int p = 5;
        int r = 1;
        for (int i = 1; i <= p; i++) {
            r *= b;
        }
        System.out.println(r);
    }
}

This will work with positive and negative bases, but not with negative powers.

Ronit Danti
  • 33
  • 1
  • 9
0

To get the exponential value without using Math.pow() you can use a loop: As long as the count is less than b (your power), your loop will have an additional "* a" to it. Mathematically, it is the same as having a Math.pow()

while (count <=b){
    a= a* a;
}
Acapulco
  • 3,373
  • 8
  • 38
  • 51
Chen Jin
  • 39
  • 8
0

Try this simple code:

public static int exponent(int base, int power) {
   int answer = 1;

   for(int i = 0; i < power; i++) {
      answer *= base;
   }

   return answer;
}
CodeZinx
  • 49
  • 1
  • 7