Reputation: 143
So I created a method that I want to calculate the square root of any given integer. For an x such as 27, I would want it to display 3√3. Or for 28, 2√7, and so on. And I'll tell you in advance, I know there are other issues in this method-- I plan to address them.
public static void root(int x) {
int [] a = new int [x]; //list of outside integers for each i
int b = x; //inside
int c = 1; //product of a[]
double sqrt = Math.sqrt(x);
if (sqrt != (int) sqrt) {
for (int i=2; i < x; i++) {
a[i] = 1;
while (x%(i^2) ==0) { //ERROR HERE
a[i] = a[i] * i;
b = b/(a[i])^2;
}
c = c * a[i];
}
System.out.println(b+"\u221A" + c);
}
else {
System.out.println((int) sqrt);
}
}
Following execution for any integer that does not yield a clean root, I receive an error that says "/ zero". Above I have the lines marked where the error is said to have occurred. Thanks in advance!
Upvotes: 1
Views: 214
Reputation: 562
Throughout your answer, you use ^
to square numbers. However, this is actually a bitwise XOR operator. Instead, use Math.pow(numToSquare, 2)
function, or simply multiply the number or expression by itself.
Upvotes: 1
Reputation: 86774
The problem is this expression
x%(i^2)
The operator ^
is not exponentiation, it is bitwise XOR. On the first iteration i
is 2
, and the result of 2 ^ 2
is ZERO. You are attempting to divide by zero (to get the remainder), which fails. Use
x%(i*i)
instead.
Upvotes: 4