Pages

Friday, 19 August 2016

Chapter 5 Exercise 16, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*5.16 (Find the factors of an integer) Write a program that reads an integer and displays 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 ProgrammingEx5_16 {
 
 public static void main(String[] args) {
  System.out.print("Enter an intergers:");
  Scanner input = new Scanner(System.in);
  int n = input.nextInt();
  int i = 2;
  String s = "";
 
  while (n != 1) {
   if (n % i == 0) {
    // add i to s and start again for the next factor
    s = s + ", " + i;
    n = n / i;
    i = 2;
   } else {
    i++;
   }
 
  }
 
  System.out.print("The factors are:" + s.substring(2) + ".");
 }
 
}

1 comment: