Java if statement find the factors of an integer

Question

We would like to write a program that reads an integer.

Display all its smallest factors in increasing order.

For example, if the input integer is 120, the output should be as follows: 2, 2, 2, 3, 5.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter first integer number: ");
        int num = input.nextInt();
        input.close();/* w ww  . java2 s.c om*/

        //your code here
    }
}




import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter first integer number: ");
        int num = input.nextInt();
        input.close();

        for (int i = 2; i < num; ) {

            if (num % i == 0) {
                System.out.print(i +" ");
                num /= i;
            } else {
                i++;
            }
        }
    }
}



PreviousNext

Related