;

Java Program to Display Factors of a Number using Recursion


Tutorialsrack 10/07/2021 Java

In this Java Program, you’ll learn how to display factors of a number using recursion. In this program, we used the following Java basics such as if..else condition.

Here is the code of the program to display factors of a number using recursion:

Program - Java Program to Display Factors of a Number using Recursion
//Java Program to Display Factors of a Number using Recursion

import java.util.Scanner;

public class JavaPrograms {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter a Number: ");
		int number = sc.nextInt();

		// find the factor of the number
		System.out.print("Factors of " + number + " are: ");
		findFactor(number, 1);
	}

	public static void findFactor(int n, int i) {

		// check i less than n
		if (i <= n) {

			// check divisible or not
			if (n % i == 0)
				System.out.print(i + "  ");

			// recursive call to check next number
			findFactor(n, i + 1);

		} // else return

	}
}
Output

Enter a Number: 

20

Factors of 20 are: 1  2  4  5  10  20  


Related Posts



Comments

Recent Posts
Tags