Java Arithmetic Operators Modulus Operator 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 an integer: ");
    int n = input.nextInt();

    int i = 2;//from  w w w  .j ava  2s. c o  m
    //your code here
    System.out.println();
  }
}




import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter an integer: ");
    int n = input.nextInt();

    int i = 2;
    while (n != 1) {
      if (n % i == 0) {
        System.out.print(i + " ");
        n /= i;
      } else {
        i++;
      }
    }
    System.out.println();
  }

}



PreviousNext

Related