Bad operand type for binary operator '^'

Trying to create a recursive method that raises the binary value for an int power for a java course. The instructions say: "However, write the code so that when n is equal, the method will return (x ^ (n / 2)) ^ 2."

This is what I have so far:

public static double powerFaster(double x, int n) { if (n == 0) { return 1; } else if ((n % 2) == 0) { return ((x ^ (n / 2.0) ^ 2.0)); //Error occurs here. } else { return x * powerFaster(x, (n - 1)); } } 
+6
source share
5 answers

^ is an XOR operator, not power. Use Math.pow() for nutrition.

However, I think you missed the exercise point.

You must return powerFaster(x, n/2) * powerFaster(x, n/2); when n is even (actually make one recursive call, save its result in a variable and propagate it yourself).

 public static double powerFaster(double x, int n) { if (n == 0) { return 1; } else if ((n % 2) == 0) { double pow = powerFaster(x, n/2); return pow * pow; } else { return x * powerFaster(x, (n - 1)); } } 
+16
source

If you do this for speed, you want to avoid using Math.pow , as this is the function you are trying to replace.

To get the squared value you can do d * d

 public static void main(String[] args) { System.out.println(powerOf(2, 9)); } public static double powerOf(double d, int n) { if (n < 0) return 1 / powerOf(d, -n); double ret = 1; if (n > 1) ret = powerOf(d * d, n / 2); if (n % 2 != 0) ret *= d; return ret; } 

prints

 512.0 
+8
source

^ - bitwise XOR used with integers :

 int a = 6; //00000110 int b = 5; //00000101 int c = a ^ b; //gives you 3 = 00000011, not 6^5 

The operation is on a binary level:

 00000110 //a 00000101 //b --------- XOR 00000011 

To execute nutrition, use Math.pow() :

 Math.pow(2.0, 1.0) //gives you 2.0 
+6
source

In Java, you should use java.lang.Math.pow (double x, double n) to raise the value of x to the power level of n

^ is an XOR operator - see this SO question for more details

+4
source

On the side of the note, do not forget that Math.pow is a really hard operation, if you use it only for a square or cube, you better do it with * operators or even for loops

Set with * operator took 4 ms

A lot with math pow took 717 ms

Set with for loop took 4 ms

Only when working with a cube in a test performed a million times

+2
source

All Articles