Factor of the given number in Java


The Java program takes a user input number and prints all its factors.

  • The program starts by importing the Scanner class from the java.util package, which is used to take user input from the console.
  • Then, the program creates a Scanner object in to read input from the console. The user is prompted to enter the number whose factors need to be found.
  • Inside the for loop, the program checks if the current value of the loop variable i is a factor of the input number n. If n is exactly divisible by i, then i is a factor of n and it is printed to the console.

Example :
     limit = 5
    5 1 => 5%1 = 0
    5 2 => 5%2 = 0
    5 3 => 5%3 = 1
    5 4 => 5%4 = 2
    5 5 => 5%5 = 0

Source Code

import java.util.Scanner;
 
public class factor {
    //Write a program to find the factor of the given number.
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter The Number : ");
        int n = in.nextInt();
        for(int i=1;i<=n;i++)
        {
            if(n%i==0){
                System.out.println(i);
            }
        }
    }
}
 
 

Output

Enter The Number : 10
1
2
5
10
To download raw file Click Here

Basic Programs