Search code examples
javamathprime-factoring

For loop in prime factorization calculator displays composite numbers as well as the loop does not restart


When the for loop detects a number that is less than the positive integer inputted by the user and perfectly divisible, it prints it and that is because the for loop just continues counting through each number. However, I need it to prime factorize the positive integer inputted by the user.

import java.util.Scanner;
public class PrimeFactor {

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);

        System.out.print("Enter a positive integer: ");
        int Number = console.nextInt();

        for (int counter =2; counter < Number; counter++) {
            if (Number % counter ==  0) {
                System.out.print(" "+counter);
            }

        }

    }

}

Solution

  • What you need to do to print all factors is to divide Number by counter when you've determined that counter is a factor. You also need to try counter again, in case there is more than one copy of a factor in a number, e.g. 12 is 2 * 2 * 3. Don't forget to print whatever Number is at the end, in case it didn't drop all the way to 1.

    for (int counter = 2; counter <= Math.sqrt(Number); counter++) {
        while (Number % counter == 0) {
            Number /= counter;
            System.out.print(" " + counter);
        }
    }
    // Print what's left.
    if (Number > 1) {
       System.out.println(" " + Number);
    }
    

    As an aside, I've also changed the for loop condition to stop at the square root of Number, because for prime factor trials, if you've found a factor greater than the square root, then you should have found the corresponding factor that is less than the square root first.

    Additionally, normal Java naming conventions would have you name the variable number in lowercase, to avoid confusion with classes such as java.lang.Number.