Euler Solution Project # 3 (Java): Debugging

I recently started work on Project Euler and I have completed the code for issue # 3. The challenge is to find the largest prime factor of a large number (600851475143). I have completed the Java code, but I have a debugging problem.

Here is the link .

When I try to run it, it returns this error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at main.main(main.java:24)

      

This is my code:

import java.util.ArrayList;
import java.util.List;

public class main {

    public static void main(String[] args) {
        long n = 600851475143L;
        int factor = 1;
        List<Integer> factors = new ArrayList<Integer>();
        List<Integer> pfactors = new ArrayList<Integer>();
        int position = 0;
        int testn = 1;

        while (factor <= n) {
            if (n % factor == 0) {
                factors.add(factor);
                factor++;
            }
            else {
                factor++;
            }

            while (position <= factors.size()) {
                while (factors.get(position) >= testn) {
                    if (factors.get(position) % testn == 0 && testn != 1 && testn != factors.get(position)) {
                        position++;
                    }
                    else {
                        pfactors.add(factors.get(position));
                        position++;
                    }
                }
            }
            int length = pfactors.size();
            System.out.println(pfactors.get(length));
        }
    }
}

      

I don't want a solution to the problem, just a way to fix the error.

+3


source to share


1 answer


List indices are in the range [0, size - 1]. So your condition while

should be position < factors.size()

instead position <= factors.size()

. Otherwise, factors.get(position)

discards IndexOutOfBoundsException

as soon as position

equal factors.size()

.



+4


source







All Articles