Reputation: 89
I am working on a java project and I have a loop that is driving me crazy.
The program takes an input, N, which is a positive integer. What I want my loop to do is this:
Lets say that N = 10. The loop will take all numbers from 1 to 10, raise it to the fifth power, and store each value in an array of length N.
It works (seemingly) correctly up until N = 73
, I think. Once N
hits 74 or above it starts to randomly give me negative numbers for 74^5. Which obviously is incorrect. The higher the number, the more negatives it gives me.
private static int _theLimit = EquationSolver.getLimit(); //input "N"
private static int length = (int) (_theLimit); //length of possible solutions array = N
static int[] _solutions = new int[length];
public static void solutionRun() {
for(int i = 1; i <=_theLimit ;) {
//theLimit refers to the input N; for numbers from 1 until N
for (int p = 0; p <= _solutions.length-1; p++) {
//solutions is an array that stores all possible solutions to ^5 from 1 to N;
_solutions[p] = i*i*i*i*i;
//p refers to the array location, increments with each new i
i++;
}
}
for(int q = 0; q<=_solutions.length-1; q++){ //outputs solutions for debugging purposes
System.out.println(_solutions[q]);
}
}
Upvotes: 4
Views: 882
Reputation: 51603
The problem is that you just passed the range that integer allows.
Int
allow numbers from -2,147,483,648 to a maximum value of 2,147,483,647 (inclusive) (source), since 74^5 = 2,219,006,624
. Thus, more that the Int
can handle.
If you want a bigger range you can use java BigInteger Class. A code example:
BigInteger pow(BigInteger base, BigInteger exponent) {
BigInteger result = BigInteger.ONE;
while (exponent.signum() > 0) {
if (exponent.testBit(0)) result = result.multiply(base);
base = base.multiply(base);
exponent = exponent.shiftRight(1);
}
return result;
}
Considerations: This may not be very efficient and might not work for negative bases or exponents. Use it as an example on how to use BigIntegers.
Instead of BigInteger, you can also use the long
type that vary from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (inclusive) (source).
Do not use double
for this purpose, since you can have precision problems.
Upvotes: 11
Reputation: 386
I don't work in Java but I hope this helps!
Try this command: public static final int MAX_VALUE
to see the maximum value an int can be in your current environment. The default is 2147483647 (which would be 2^31 - 1). 74^5 = 2073071593 which works but, 75^5 = 2219006624 which is too high. Use BigInteger to support your number range.
Upvotes: 0