使用递归查找 2 个数字的乘积的 C# 程序
给定两个数字 x 和 y 使用递归找到乘积。递归是一个函数直接或间接调用自身并且相应的函数称为递归函数的过程。它用于轻松解决问题,如本文中使用递归我们将找到两个数字的乘积。
例子:
Input : x = 10, y = 3
Output : 30
Input : x = 70, y = 4
Output : 280
方法:
To print the product of two number using recursion follow the following steps:
- For our task we have two numbers, i.e., x, y.
- Initialize a variable result with value zero.
- Recursively add the x to result for y times.
- Take the base condition as y == 0. When y is equal to 0 then return from function.
- At The end of iteration the result variable will contain the product of x, y.
例子:
C#
// C# program to display the product of
// two numbers using Recursion
using System;
class GFG{
// Recursive function for calculating
// product of two numbers.
static int product(int x, int y)
{
// If y is equal to zero then return 0
if (y == 0)
return 0;
// Recursively calculate
// y times sum of x
else
return (x + product(x, y - 1));
}
// Driver code
public static void Main ()
{
int x = 10, y = 3;
Console.Write(product(x, y));
}
}
C#
// C# program to display the product of
// two numbers using Recursion
using System;
class GFG{
// Recursive function for calculating
// product of two numbers.
static int product(int x, int y)
{
// If y is equal to zero then return 0
if (y == 0)
return 0;
// Recursively calculate
// y times sum of x
else
return(x + product(x, y - 1));
}
// Driver code
public static void Main()
{
int x = 3, y = 150;
// Swapping the x and y if the y > x.
if (x < y)
Console.Write(product(y, x));
else
Console.Write(product(x, y));
}
}
输出
30
如果 y 大于 x,我们可以通过交换 x 和 y 来优化此代码。让我们假设 x = 3 和 y = 150 如果我们遵循上述程序,那么 x 会递归添加 150 次,但是通过交换 x,y(即 x = 150, y = 3)我们只需要递归添加 x 3次。
C#
// C# program to display the product of
// two numbers using Recursion
using System;
class GFG{
// Recursive function for calculating
// product of two numbers.
static int product(int x, int y)
{
// If y is equal to zero then return 0
if (y == 0)
return 0;
// Recursively calculate
// y times sum of x
else
return(x + product(x, y - 1));
}
// Driver code
public static void Main()
{
int x = 3, y = 150;
// Swapping the x and y if the y > x.
if (x < y)
Console.Write(product(y, x));
else
Console.Write(product(x, y));
}
}
输出
450