Program to find all Factors of a Number using recursion
Given a number N, the task is to print all the factors of N using recursion.
Examples:
Input: N = 16
Output: 1 2 4 8 16
Explanation:
1, 2, 4, 8, 16 are the factors of 16. A factor is a number which divides the number completely.
Input: N = 8
Output: 1 2 4 8
Approach: The idea is to create a function that takes 2 arguments. The function is recursively called from 1 to N and in every call, if the number is a factor of N, then it is printed. The recursion will stop when the number exceeds N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void factors( int n, int i)
{
if (i <= n) {
if (n % i == 0) {
cout << i << " " ;
}
factors(n, i + 1);
}
}
int main()
{
int N = 16;
factors(N, 1);
}
|
Java
class GFG {
static void factors( int n, int i)
{
if (i <= n) {
if (n % i == 0 ) {
System.out.print(i + " " );
}
factors(n, i + 1 );
}
}
public static void main(String args[])
{
int N = 16 ;
factors(N, 1 );
}
}
|
Python3
def factors(n, i):
if (i < = n):
if (n % i = = 0 ):
print (i, end = " " );
factors(n, i + 1 );
if __name__ = = '__main__' :
N = 16 ;
factors(N, 1 );
|
C#
using System;
class GFG {
static void factors( int n, int i)
{
if (i <= n) {
if (n % i == 0) {
Console.WriteLine(i + " " );
}
factors(n, i + 1);
}
}
public static void Main()
{
int n = 16;
factors(n, 1);
}
}
|
Javascript
<script>
function factors(n, i)
{
if (i <= n) {
if (n % i == 0) {
document.write(i + " " );
}
factors(n, i + 1);
}
}
var N = 16;
factors(N, 1);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
30 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...