In: Computer Science
in code c++ describe a recursive algorithm for multiplying two nonnegative integers x and y based on the fact that xy = 2(x · (y/2)) when y is even and xy = 2(x · ⌊y/2⌋) + x when y is odd, together with the initial condition xy = 0 when y = 0.
// C++ Program to find Product
// of 2 Numbers using Recursion
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
// recursive function to calculate
// multiplication of two numbers
int product(int x, int y)
{ if(y==0) //return ) if y is 0 intial condition
return 0;
// if y is even
else if (y%2==0)
return (2*product(x, y/2));
// if y is odd
else
return (x + 2*product(x, floor((y -
1)/2)));
// if any of the two numbers is
// zero return zero
}
// Driver Code
int main()
{
int x = 23, y = 3;
cout << product(x, y);
return 0;
}
Output :
69
Thumbs up will be appreciated