📜  递归程序为n个整数的GCD打印公式

📅  最后修改于: 2021-05-07 09:19:03             🧑  作者: Mango

给定函数gcd(a,b)来找到两个数字的GCD(最大公约数)。还已知可以通过gcd(a,gcd(b,c))找到三个元素的GCD,类似地,对于四个元素,也可以通过gcd(a,gcd(b,gcd(c,d))找到GCD。 )。给定正整数n 。工作是使用给定的gcd()函数打印公式以找到n个整数的GCD。
例子

Input : n = 3
Output : gcd(int, gcd(int, int))

Input : n = 5
Output : gcd(int, gcd(int, gcd(int, gcd(int, int))))

方法:想法是使用递归来打印单行命令。现在,要编写一个递归函数,例如recursiveFun(n),所需的字符串由gcd(int,+ recursiveFun(n – 1)+)组成。这意味着recursiveFun(n)应该返回一个包含对自身的调用的字符串,并且为了评估该值,递归函数将再次从n – 1开始。这将依次返回另一个字符串,其中包含对n – 1,直到n == 1为止,递归函数改为返回字符串“ int”。
下面是上述方法的实现:

C++
// CPP Program to print single line command
// to find the GCD of n integers
#include 
using namespace std;
 
// Function to print single line command
// to find GCD of n elements.
string recursiveFun(int n)
{
    // base case
    if (n == 1)
        return "int";
 
    // Recursive Step
    return "gcd(int, " + recursiveFun(n - 1) + ")";
}
 
// Driver Program
int main()
{
    int n = 5;
 
    cout << recursiveFun(n) << endl;
 
    return 0;
}


Java
// Java Program to print
// single line command to
// find the GCD of n integers
class GFG
{
     
// Function to print single
// line command to find GCD
// of n elements.
static String recursiveFun(int n)
{
    // base case
    if (n == 1)
        return "int";
 
    // Recursive Step
    return "gcd(int, " +
            recursiveFun(n - 1) + ")";
}
 
// Driver Code
public static void main(String [] arg)
{
    int n = 5;
 
    System.out.println(recursiveFun(n));
}
}
 
// This code is contributed
// by Smitha


Python3
# Python 3 Program to print single line
# command to find the GCD of n integers
 
# Function to print single line command
# to find GCD of n elements.
def recursiveFun(n):
     
    # base case
    if (n == 1):
        return "int"
 
    # Recursive Step
    return "gcd(int, " + recursiveFun(n - 1) + ")"
 
# Driver Code
if __name__ == '__main__':
    n = 5
    print(recursiveFun(n))
 
# This code is contributed
# by PrinciRaj1992


C#
// C# Program to print single
// line command to find the
// GCD of n integers
using System;
class GFG
{
     
// Function to print single
// line command to find GCD
// of n elements.
static String recursiveFun(int n)
{
    // base case
    if (n == 1)
        return "int";
 
    // Recursive Step
    return "gcd(int, " +
            recursiveFun(n - 1) + ")";
}
 
// Driver Code
public static void Main()
{
    int n = 5;
 
    Console.Write(recursiveFun(n));
}
}
 
// This code is contributed
// by smitha


Javascript


输出:
gcd(int, gcd(int, gcd(int, gcd(int, int))))

时间复杂度: O(N),其中N是给定的数字。