Issue
import java.util.ArrayList;
public class LargestPrimeFactor {
private static long maxNum;
public LargestPrimeFactor(long maxNum) {
LargestPrimeFactor.maxNum = maxNum;
ArrayList<Long> listOfPrimes = new ArrayList<>();
listOfPrimes.add(2L);
for (long i = 3; i < maxNum / 2; i++) {
if (i % 2 == 1 && isPrime(i)) {
listOfPrimes.add(i);
}
}
// for (long i = 0; i < listOfPrimes.size(); i++) {
// System.out.println(listOfPrimes.get((int) i));
// }
for (long i = listOfPrimes.size() -1; i >= 0; i--) {
if (maxNum % ((long) listOfPrimes.get(i)) == 0) {
System.out.println("Max Prime Factor is: " + listOfPrimes.get(i));
break;
}
// System.out.println(listOfPrimes.get((int) i));
}
}
private boolean isPrime(long num) {
for (long i = 2; i < num; i++ ) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
The problem in my code is following: enen if I autobox to <Long>
, Java requires to cast to int
when I use listOfPrimes::get
. It is not desired because the numbers I would work with would be out of scope. How can I fix that?
Solution
In this loop
for (long i = listOfPrimes.size() - 1; i >= 0; i--) {
if (maxNum % ((long) listOfPrimes.get(i)) == 0) {
System.out.println("Max Prime Factor is: " + listOfPrimes.get(i));
break;
}
}
You should change the type of i
from long
to int
. This is not saying that the numbers in listOfPrimes
must be int
, it only says that the count of elements in listOfPrimes
must be representable with a 32bit signed integer.
Indeed, listOfPrimes.size()
returns an integer, not a long. In Java, the length of an array is always specified by an int
. Hence an array cannot hold more elements than an int
can count. As a result, an ArrayList
cannot hold more elements either.
Moreover, the Collection.size()
method returns an int
, so that none of the classes that implement the Collection
interface can hold more values.
Edit: As mentioned by user16320675 in the comments, collections can hold more elements than Integer.MAX_VALUE
. You just have to be careful about what size()
returns in those cases: it returns Integer.MAX_VALUE
rather than the actual size.
Answered By - Daniel Junglas