Factors of a number using Java

Factors of a number using java :

In this article we will create a java program to find factors(divisors) of a number. Factors of a number are the numbers which completely divides that number.

Suppose a number is 8, so its factors will be 1 , 2 , 4 and 8.

Point to remember :

  • Factors of a number are always starts with 1 and ends with the number itself.
  • All the factors of a number are always smaller than the number whose factors is to be calculated.
Factors of a number using Java

Working :

Step 1 : Ask the user to enter a number.

Step 2 : Use a loop to calculate all the factors of the number which is entered by the user.

Step 3 : Start the loop with 1 and end it with the number whose factors need to be calculated.

Step 4 : Print the result in every iteration

Code  in Java :

//Java program to find factors of a number
import java.util.Scanner;
public class factors_of_a_number
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
int number = sc.nextInt();
System.out.println("Factors of "+number+" are :");
//loop for finding factors of a number
for(int i = 1 ; i <= number ; i++)
{
if(number % i == 0)
//printing factors
System.out.print(i+" ");
}
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter a number : 12
Factors of 12 are :
1 2 3 4 6 12