Dados dos números N y M. La tarea es encontrar el producto de los 2 números usando recursividad.
Nota : Los números pueden ser tanto positivos como negativos.
Ejemplos :
Input : N = 5 , M = 3 Output : 15 Input : N = 5 , M = -3 Output : -15 Input : N = -5 , M = 3 Output : -15 Input : N = -5 , M = -3 Output:15
Una solución recursiva al problema anterior solo para números positivos ya se discutió en el artículo anterior . En esta publicación, se analiza una solución recursiva para encontrar el producto de números positivos y negativos.
A continuación se muestra el enfoque paso a paso:
- Compruebe si uno o ambos números son negativos.
- Si el número pasado en el segundo parámetro es negativo, intercambie los parámetros y vuelva a llamar a la función.
- Si ambos parámetros son negativos, vuelva a llamar a la función y pase los valores absolutos de los números como parámetros.
- Si n>m llame a la función con parámetros intercambiados para reducir el tiempo de ejecución de la función.
- Siempre que m no sea 0, siga llamando a la función con el subcaso n, m-1 y devuelva n + multrecur(n, m-1).
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to find product of two numbers // using recursion #include <iostream> using namespace std; // Recursive function to calculate the product // of 2 integers int multrecur(int n, int m) { // case 1 : n<0 and m>0 // swap the position of n and m to keep second // parameter positive if (n > 0 && m < 0) { return multrecur(m, n); } // case 2 : both n and m are less than 0 // return the product of their absolute values else if (n < 0 && m < 0) { return multrecur((-1 * n), (-1 * m)); } // if n>m , swap n and m so that recursion // takes less time if (n > m) { return multrecur(m, n); } // as long as m is not 0 recursively call multrecur for // n and m-1 return sum of n and the product of n times m-1 else if (m != 0) { return n + multrecur(n, m - 1); } // m=0 then return 0 else { return 0; } } // Driver code int main() { cout << "5 * 3 = " << multrecur(5, 3) << endl; cout << "5 * (-3) = " << multrecur(5, -3) << endl; cout << "(-5) * 3 = " << multrecur(-5, 3) << endl; cout << "(-5) * (-3) = " << multrecur(-5, -3) << endl; return 0; }
Java
//Java program to find product of two numbers //using recursion public class GFG { //Recursive function to calculate the product //of 2 integers static int multrecur(int n, int m) { // case 1 : n<0 and m>0 // swap the position of n and m to keep second // parameter positive if (n > 0 && m < 0) { return multrecur(m, n); } // case 2 : both n and m are less than 0 // return the product of their absolute values else if (n < 0 && m < 0) { return multrecur((-1 * n), (-1 * m)); } // if n>m , swap n and m so that recursion // takes less time if (n > m) { return multrecur(m, n); } // as long as m is not 0 recursively call multrecur for // n and m-1 return sum of n and the product of n times m-1 else if (m != 0) { return n + multrecur(n, m - 1); } // m=0 then return 0 else { return 0; } } //Driver code public static void main(String[] args) { System.out.println("5 * 3 = " + multrecur(5, 3)); System.out.println("5 * (-3) = " + multrecur(5, -3)); System.out.println("(-5) * 3 = " + multrecur(-5, 3)); System.out.println("(-5) * (-3) = " +multrecur(-5, -3)); } }
Python3
# Python 3 program to find product of two numbers # using recursion # Recursive function to calculate the product # of 2 integers def multrecur(n, m) : # case 1 : n<0 and m>0 # swap the position of n and m to keep second # parameter positive if n > 0 and m < 0 : return multrecur(m,n) # case 2 : both n and m are less than 0 # return the product of their absolute values elif n < 0 and m < 0 : return multrecur((-1 * n),(-1 * m)) # if n>m , swap n and m so that recursion # takes less time if n > m : return multrecur(m, n) # as long as m is not 0 recursively call multrecur for # n and m-1 return sum of n and the product of n times m-1 elif m != 0 : return n + multrecur(n, m-1) # m=0 then return 0 else : return 0 # Driver Code if __name__ == "__main__" : print("5 * 3 =",multrecur(5, 3)) print("5 * (-3) =",multrecur(5, -3)) print("(-5) * 3 =",multrecur(-5, 3)) print("(-5) * (-3) =",multrecur(-5, -3)) # This code is contributed by ANKITRAI1
C#
// C# program to find product of // two numbers using recursion using System; class GFG { // Recursive function to calculate // the product of 2 integers static int multrecur(int n, int m) { // case 1 : n<0 and m>0 // swap the position of n and m // to keep second parameter positive if (n > 0 && m < 0) { return multrecur(m, n); } // case 2 : both n and m are less than 0 // return the product of their absolute values else if (n < 0 && m < 0) { return multrecur((-1 * n), (-1 * m)); } // if n>m , swap n and m so that // recursion takes less time if (n > m) { return multrecur(m, n); } // as long as m is not 0 recursively // call multrecur for n and m-1 return // sum of n and the product of n times m-1 else if (m != 0) { return n + multrecur(n, m - 1); } // m=0 then return 0 else { return 0; } } // Driver code public static void Main() { Console.WriteLine("5 * 3 = " + multrecur(5, 3)); Console.WriteLine("5 * (-3) = " + multrecur(5, -3)); Console.WriteLine("(-5) * 3 = " + multrecur(-5, 3)); Console.WriteLine("(-5) * (-3) = " + multrecur(-5, -3)); } } // This code is contributed by anuj_67
PHP
<?php // PHP program to find product of // two numbers using recursion // Recursive function to calculate // the product of 2 integers function multrecur($n, $m) { // case 1 : n<0 and m>0 // swap the position of n and m to keep second // parameter positive if ($n > 0 && $m < 0) { return multrecur($m, $n); } // case 2 : both n and m are less than 0 // return the product of their absolute values else if ($n < 0 && $m < 0) { return multrecur((-1 * $n), (-1 * $m)); } // if n>m , swap n and m so that // recursion takes less time if ($n > $m) { return multrecur($m, $n); } // as long as m is not 0 recursively call multrecur for // n and m-1 return sum of n and the product of n times m-1 else if ($m != 0) { return $n + multrecur($n, $m - 1); } // m=0 then return 0 else { return 0; } } // Driver code echo "5 * 3 = " . multrecur(5, 3) . "\n"; echo "5 * (-3) = " . multrecur(5, -3) . "\n"; echo "(-5) * 3 = " . multrecur(-5, 3) . "\n"; echo "(-5) * (-3) = " . multrecur(-5, -3) . "\n"; // This code is contributed by mits ?>
Javascript
<script> // Javascript program to find product // of two numbers using recursion // Recursive function to calculate the // product of 2 integers function multrecur(n, m) { // case 1 : n<0 and m>0 // Swap the position of n and m to // keep second parameter positive if (n > 0 && m < 0) { return multrecur(m, n); } // case 2 : both n and m are less than 0 // return the product of their absolute values else if (n < 0 && m < 0) { return multrecur((-1 * n), (-1 * m)); } // If n>m , swap n and m so that recursion // takes less time if (n > m) { return multrecur(m, n); } // As long as m is not 0 recursively // call multrecur for n and m-1 // return sum of n and the product // of n times m-1 else if (m != 0) { return n + multrecur(n, m - 1); } // m=0 then return 0 else { return 0; } } // Driver code document.write("5 * 3 = " + multrecur(5, 3) + "<br>"); document.write("5 * (-3) = " + multrecur(5, -3) + "<br>"); document.write("(-5) * 3 = " + multrecur(-5, 3) + "<br>"); document.write("(-5) * (-3) = " + multrecur(-5, -3) + "<br>"); // This code is contributed by rutvik_56 </script>
Producción:
5 * 3 = 15 5 * (-3) = -15 (-5) * 3 = -15 (-5) * (-3) = 15
Complejidad de tiempo: O(max(N, M))
Espacio auxiliar: O(max(N, M))
Publicación traducida automáticamente
Artículo escrito por neverSettle y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA