I have a simple Java method, which is suppose to compute a list of prime divisors of a certain number.
public class Factors {
public static List<Integer> fac(List<Integer> factors, int number) {
if(number < 2) {
throw new IllegalArgumentException("Number must be greater than one");
}
for (int i = 2; i <= number; i++) {
while (number%i == 0) {
factors.add(i);
number /= i;
}
}
return factors;
}
public static void main(String [] args)
{
final long startTime = System.currentTimeMillis();
ArrayList<Integer> factors = new ArrayList<>();
System.out.println(fac(factors, 2147483647));
final long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime) );
}
}
This code works fine, except you feed Integer.MAX_VALUE into it; in that case giving:
java.lang.OutOfMemoryError: Java heap space
Initially, I thought, that this is due to, that ArrayList initialization was inside a method, but after removing, the same error persists.
Moreover, this:
public static List<Long> facrec2(List<Long> list, long number) {
if (number < 2) {
return list;
}
if (number == 2) {
list.add(2L);
return list;
}
for (long i = 2; i <= number; i++) {
while (number % i == 0) {
number /= i;
list.add(i);
return facrec2(list, number);
}
}
return null;
}
method works for max values (after changing signature to Integer, works for Integer max value too). Logic of both suppose to be the same, only recursive implementation of the second makes the difference...