Ejercicio
Función Multiply & MultiplyR
Objetivo
Crea dos funciones, Multiplicar y Multiplicar, para calcular el producto de dos números usando sumas. La primera versión debe ser iterativa, y la segunda debe ser recursiva.
Código de Ejemplo
// Import the System namespace to use basic classes like Console
using System;
class Program
{
// Function to multiply two numbers iteratively using addition
public static int Multiply(int a, int b)
{
int product = 0; // Variable to store the product
// Add 'a' to itself 'b' times to simulate multiplication
for (int i = 0; i < Math.Abs(b); i++)
{
product += a; // Add 'a' repeatedly
}
// If b is negative, the product should be negative
if (b < 0)
{
product = -product; // Negate the product
}
return product;
}
// Function to multiply two numbers recursively using addition
public static int MultiplyR(int a, int b)
{
// Base case: if b is 0, the product is 0
if (b == 0)
{
return 0;
}
else
{
// Recursive case: add 'a' recursively and handle negative b
if (b < 0)
{
return -a + MultiplyR(a, b + 1); // For negative b, subtract 'a'
}
else
{
return a + MultiplyR(a, b - 1); // For positive b, add 'a'
}
}
}
// Main function to test the Multiply and MultiplyR functions
public static void Main()
{
// Test the Multiply function
Console.WriteLine("Iterative Multiply:");
Console.WriteLine("3 * 4 = " + Multiply(3, 4)); // Expected output: 12
Console.WriteLine("-3 * 4 = " + Multiply(-3, 4)); // Expected output: -12
Console.WriteLine("3 * -4 = " + Multiply(3, -4)); // Expected output: -12
Console.WriteLine("0 * 4 = " + Multiply(0, 4)); // Expected output: 0
// Test the MultiplyR function
Console.WriteLine("\nRecursive Multiply:");
Console.WriteLine("3 * 4 = " + MultiplyR(3, 4)); // Expected output: 12
Console.WriteLine("-3 * 4 = " + MultiplyR(-3, 4)); // Expected output: -12
Console.WriteLine("3 * -4 = " + MultiplyR(3, -4)); // Expected output: -12
Console.WriteLine("0 * 4 = " + MultiplyR(0, 4)); // Expected output: 0
}
}