原文:

给定两个数 x 和 y,用递归求积。 例:

input : x = 5, y = 2
output : 10
input : x = 100, y = 5
output : 500

方法 1)如果 x 小于 y,交换两个变量值 2)递归求 y 乘以 x 的和 3)如果其中任何一个变为零,返回 0

c

// c   program to find product
// of 2 numbers using recursion
#include 
using namespace std;
// recursive function to calculate
// multiplication of two numbers
int product(int x, int y)
{
    // if x is less than
    // y swap the numbers
    if (x < y)
        return product(y, x);
    // iteratively calculate
    // y times sum of x
    else if (y != 0)
        return (x   product(x, y - 1));
    // if any of the two numbers is
    // zero return zero
    else
        return 0;
}
// driver code
int main()
{
    int x = 5, y = 2;
    cout << product(x, y);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java program to find product
// of 2 numbers using recursion
import java.io.*;
import java.util.*;
class gfg
{
    // recursive function to calculate
    // multiplication of two numbers
    static int product(int x, int y)
    {
        // if x is less than
        // y swap the numbers
        if (x < y)
            return product(y, x);
        // iteratively calculate
        // y times sum of x
        else if (y != 0)
            return (x   product(x, y - 1));
        // if any of the two numbers is
        // zero return zero
        else
            return 0;
    }
    // driver code
    public static void main (string[] args)
    {
        int x = 5, y = 2;
        system.out.println(product(x, y));
    }
}
// this code is contributed by gitanjali.

python 3

# python3 to find product of
# 2 numbers using recursion
# recursive function to calculate
# multiplication of two numbers
def product( x , y ):
    # if x is less than y swap
    # the numbers
    if x < y:
        return product(y, x)
    # iteratively calculate y
    # times sum of x
    elif y != 0:
        return (x   product(x, y - 1))
    # if any of the two numbers is
    # zero return zero
    else:
        return 0
# driver code
x = 5
y = 2
print( product(x, y))
# this code is contributed
# by abhishek sharma44.

c

// c# program to find product
// of 2 numbers using recursion
using system;
class gfg
{
    // recursive function to calculate
    // multiplication of two numbers
    static int product(int x, int y)
    {
        // if x is less than
        // y swap the numbers
        if (x < y)
            return product(y, x);
        // iteratively calculate
        // y times sum of x
        else if (y != 0)
            return (x   product(x, y - 1));
        // if any of the two numbers is
        // zero return zero
        else
            return 0;
    }
    // driver code
    public static void main ()
    {
        int x = 5, y = 2;
        console.writeline(product(x, y));
    }
}
// this code is contributed by vt_m.

服务器端编程语言(professional hypertext preprocessor 的缩写)


java 描述语言


输出:

10