In: Computer Science
Implement and complement the recursive code to compute the product of two positive integers, x and y, using only addition and/or subtraction. The function will take as its arguments two integers to multiply together ( x x y ) and will return the product.
Hint: consider the following:
6 x 1 = 6
6 x 2 = 6 + (6 x 1)
6 x 3 = 6 + (6 x 2) = 6 + [6 + (6 x 1)] = 6 + 6 + 6
#include<iostream>
using namespace std;
// Implement this product recursive function.
int product(int x, int y)
{
}
int main()
{
int x = 40, y = 10;
cout << "product(" << x << ", " << y
<< ")=";
cout << product(x, y) << endl;
return 0;
}
#include <bits/stdc++.h>
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;
}
----------------------------------------------------------------------------------------------------------------------------------------------------
#include<iostream>
using namespace std;
class GFG
{
/* function to multiply two numbers x and y*/
public : int multiply(int x, int y)
{
/* 0 multiplied with anything gives 0 */
if(y == 0)
return 0;
/* Add x one by one */
if(y > 0 )
return (x + multiply(x, y-1));
/* the case where y is negative */
if(y < 0 )
return -multiply(x, -y);
}
};
// Driver code
int main()
{
GFG g;
cout << endl << g.multiply(5, -11);
getchar();
return 0;
}