Calculating the Factors of a Number in Java

Problem:

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.


Output:

1202 2 2 3 5


Solution:

public class Factors
{
  public static void main (String[] args)
  {
    java.util.Scanner scan = new java.util.Scanner(System.in);
    int N = scan.nextInt();
    for (int i =2;N>1;i++)
    {
      if(N%i == 0)
      {
        System.out.print(i +" ");
        
      N/=i;
      i=1;
      }
    }
  }
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact