问题
The code is supposed to give back the biggest prime number. More about the task here: https://projecteuler.net/problem=3
int checkFactors(double na) {
long n = (long) na;
int biggestPrimeFactor = 0;
for (int i = 1; i < n; i++)
if (n % i == 0 && isPrimFaktor(i) && i > biggestPrimeFactor)
biggestPrimeFactor = i;
return biggestPrimeFactor;
}
boolean isPrimeFactor(int n) {
int length= 0;
for (int i = n; i > 0; i--)
if (n % i == 0)
length++;
if (length== 2)
return true;
return false;
}
I decided to make the parameter of checkFactors() a double because I tried to test why my code didn't work properly.
System.out.println(checkFactors(13195));
works and returns "29".
However, System.out.println(checkFactors(600851475143));
does not work,
"600851475143 of type int is out of range".
System.out.println(checkFactors(600851475143.0));
does compile but gives me after a couple of seconds an ArithmeticException.
回答1:
600851475143 of type int is out of range
- This number is bigger than
int
can store. Appending.0
to the number converts the number into adouble
which can represent that number - Instead of
.0
you can docheckFactors(600851475143d)
which ensure the number is a double and not an int
回答2:
Use long as a data type for na and also biggestPrimeFactor. The values are too large for storing in an int variable.
回答3:
Try to make Your parameter back to long
and make letter L
after your large number like this 600851475143L
, I think it will work
来源:https://stackoverflow.com/questions/27923619/project-euler-3-out-of-integer-range-java