Search code examples
javaprimesprime-factoringfactorization

Java program for prime factorization prints too much


I was given a problem to solve at school, which goes like this:

Write a program that reads a positive integer greater than 1 and then prints out the prime factors of the number in increasing order. If the number is a prime, print out that number followed by a statement saying that it is a prime, as shown in one of the examples.

So then I wrote this program and it has expected behaviour when I put in an actual prime. If I put in 97, the output will be "97 is a prime number." as supposed.

But when I input 120 it prints "2 2 2 3 5 is a prime number" where expected behaviour would be only to print the numbers and not the "is a prime number" text.

Method that checks if the input number is a prime, and if so, prints the factors of it:

public static void primeFactors(int n) {

    while (n % 2 == 0) {
        System.out.print(2 + " ");
        n = n/2;
    }

    for (int i = 3; i <= Math.sqrt(n); i = i+2) {
        while (n % i == 0) {
            System.out.print(i + " ");
            n = n/i;
        }
    }

    if (n > 2) {
        System.out.print(n + " is a prime number.");
    }
}

Main method:

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);
    int n = reader.nextInt();
    primeFactors(n);
}

So I'd like some help figuring out how to make it so that the "is a prime number." ending is ONLY printed when the entered number specifically is a prime.


Solution

  • You could save the parameter n into a variable to keep it.

    int input = n;
    

    Then in the end change your output to the following:

    if (n > 2) {
        System.out.print(n);
    }
    if (n == input) {
        System.out.print(" is a prime number.");
    }