Dado un número N , la tarea es imprimir todos los factores de N usando recursividad.
Ejemplos:
Entrada: N = 16
Salida: 1 2 4 8 16
Explicación:
1, 2, 4, 8, 16 son los factores de 16. Un factor es un número que divide el número por completo.
Entrada: N = 8
Salida: 1 2 4 8
Enfoque: La idea es crear una función que tome 2 argumentos. La función se llama recursivamente de 1 a N y en cada llamada, si el número es un factor de N, entonces se imprime. La recursividad se detendrá cuando el número exceda N.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to find all the factors // of a number using recursion #include <bits/stdc++.h> using namespace std; // Recursive function to // print factors of a number void factors(int n, int i) { // Checking if the number is less than N if (i <= n) { if (n % i == 0) { cout << i << " "; } // Calling the function recursively // for the next number factors(n, i + 1); } } // Driver code int main() { int N = 16; factors(N, 1); }
Java
// Java program to find all the factors // of a number using recursion class GFG { // Recursive function to // print factors of a number static void factors(int n, int i) { // Checking if the number is less than N if (i <= n) { if (n % i == 0) { System.out.print(i + " "); } // Calling the function recursively // for the next number factors(n, i + 1); } } // Driver code public static void main(String args[]) { int N = 16; factors(N, 1); } }
Python3
# Python3 program to find all the factors # of a number using recursion # Recursive function to # prfactors of a number def factors(n, i): # Checking if the number is less than N if (i <= n): if (n % i == 0): print(i, end = " "); # Calling the function recursively # for the next number factors(n, i + 1); # Driver code if __name__ == '__main__': N = 16; factors(N, 1); # This code is contributed by Rajput-Ji
C#
// C# program to find all the factors // of a number using recursion using System; class GFG { // Recursive function to // print factors of a number static void factors(int n, int i) { // Checking if the number is less than N if (i <= n) { if (n % i == 0) { Console.WriteLine(i + " "); } // Calling the function recursively // for the next number factors(n, i + 1); } } // Driver code public static void Main() { int n = 16; factors(n, 1); } }
Javascript
<script> // Javascript program to find all the factors // of a number using recursion // Recursive function to // print factors of a number function factors(n, i) { // Checking if the number is less than N if (i <= n) { if (n % i == 0) { document.write(i + " "); } // Calling the function recursively // for the next number factors(n, i + 1); } } // Driver code var N = 16; factors(N, 1); </script>
Producción:
1 2 4 8 16
Complejidad de tiempo: O(N)
Espacio Auxiliar: O(N)