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.
Try to make Your parameter back to
long
and make letterL
after your large number like this600851475143L
, I think it will workUse long as a data type for na and also biggestPrimeFactor. The values are too large for storing in an int variable.
600851475143 of type int is out of range
int
can store. Appending.0
to the number converts the number into adouble
which can represent that number.0
you can docheckFactors(600851475143d)
which ensure the number is a double and not an int