HomeJavaJava Program to Display Factors of a Number

Java Program to Display Factors of a Number

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 SNIPPET
import 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 SNIPPET
public 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. 

Share:

Leave a Reply

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022