Question

I'm new to Java. I found a website called project eulder and was practicing on a problem. I don't understand why the following program does not display anything but when I put System.out.println(max); into the for loop it works but displaying all the prime numbers including the biggest. Who do I only the display the biggest prime number?

public class LargestPrimeFactor {

    public static void main(String[] args) {
        long x = 600851475143L;
        int max = 0;
        for (int i = 1; i <= x; i++) {
            if (x % i == 0)
                if (isPrime(i))
                    max = i;
        }
        System.out.println(max);

    }

    public static boolean isPrime(int n) {
        for (int i = 2; i < n; i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
}
Was it helpful?

Solution

You have written an infinite loop: 600851475143L is greater than the maximum value that can be stored in an int, so i <= x will always be true.

Changing i and all the other relevant variables to long may solve this issue, but you'll still have to rethink your algorithm. Checking if 600851475143 numbers are prime is just going to take too long.

Hint: once you have found a number that divides x, you can divide x by that number... (Hope this doesn't spoil the fun)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top