📌  相关文章
📜  程序使用递归找到一个数字的所有因子

📅  最后修改于: 2021-05-05 02:01:27             🧑  作者: Mango

给定数字N ,任务是使用递归打印N的所有因子。
例子:

方法:我们的想法是创建一个函数,需要两个参数。该函数从1到N递归调用,并且在每次调用中,如果数字是N的因数,则将其打印出来。当数字超过N时,递归将停止。
下面是上述方法的实现:

C++
// C++ program to find all the factors
// of a number using recursion
 
#include 
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


输出:
1 2 4 8 16

时间复杂度: O(N)