Recursion: Given 2 numbers find the product of the numbers, using recursion

Problem Statement:

Given 2 numbers find the product of the numbers, using recursion

Example:

Input:

m = 10
n = 2

Output: 20

Solution Explanation:

We will use recursion to solve the problem.

Multiplication of x * y is nothing but adding x, y times.

So we will make a recursive call and add x, y times.

Time Complexity: O((m,n))
Space Complexity: O((m,n))

Code Solution

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

int solution(int x, int y)
{
    if (y != 0)
        return (x + solution(x, y - 1));

    else
        return 0;
}

int main()
{
    int x = 5, y = 2;
    cout << solution(x, y);
    return 0;
}

Output

10
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *