In this program, we’ll learn how to Display Factors of a Number in your Java program.
How to Display Factors of a Number in Java?
Example 1: using recursion
RUN CODE SNIPPETimport java.util.Scanner;
public class Main {
public static void findFactor(int n, int i) {
if(i <= n) {
if(n%i == 0)
System.out.print(i+"\t");
findFactor(n, i+1);
}
}
public static void main(String[] args) {
int number = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number:: ");
number = scan.nextInt();
System.out.print("The factors are:: ");
findFactor(number, 1);
scan.close();
}
}OUTPUT
Enter a number: 15 The factors are: 1 3 5 15
Example 2: Factors of a Positive Numbers
RUN CODE SNIPPETpublic class Main {
public static void main(String[] args) {
int number = 150;
System.out.print("Factors of " + number + " are: ");
for (int i = 1; i <= number; ++i) {
if (number % i == 0) {
System.out.print(i + " ");
}
}
}
}OUTPUT
Factors of 150 are: 1 2 3 5 6 10 15 25 30 50 75 150
In the above program, the number to which we are going to find the factorial is stored in the variable number.