Factors of a number using Java

find factorial of number using java

Factors of a number using java :

In this article we will see a program to find Factors of a number using Java programming language. To find answer of a number we will use a loop in which we start dividing the number with 1 up to the number itself and the numbers which perfectly divides the number are the factors.

For Example: 21

Factors are: 1, 3, 7, 21

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 variable.

Step 4 : Print the result in every iteration

factor of number in java

Factors of a number using Java :

import java.util.Scanner;
public class Main
{
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 :");

for(int i = 1 ; i <= number ; i++)
{
if(number % i == 0)

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