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

Your email address will not be published. Required fields are marked *

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024