Product of Two Numbers

Last Updated : 23 Jul, 2025

Given two numbers, a and b. Return the product of both the numbers.

Examples:

Input: a = 4, b = 5
Output: 20

Input: a = 3, b = 5
Output: 15

Try It Yourself
redirect icon

[Expected Approach] Using Multiplication Operator - O(1) Time and O(1) Space

We can find the product of both the numbers by using the multiplication operator (*). This operator works by taking two operands and returns their product as the result.

C++
#include <iostream>
using namespace std;

int main()
{
    int a = 4, b = 5;

    // print the product of a and b
    cout << (a * b) << endl;
    return 0;
}
Java
class GfG {
    public static void main(String[] args) {
        int a = 4, b = 5;
        
        // print the product of a and b
        System.out.println(a * b);
    }
}
Python
if __name__ == "__main__":
    a = 4
    b = 5
    
    # print the product of a and b
    print(a * b)
JavaScript
// Driver Code
let a = 4, b = 5;

// print the product of a and b
console.log(a * b);

Output
20

[Alternate Approach] Using Recursion - O(min(a, b)) Time and O(min(a, b)) Space

To find the product of two numbers, x and y, using recursion, you can follow this approach:

  • Base Case: If y equals 0, return 0 (since any number multiplied by 0 results in 0).
  • Recursive Case: Add x to the result and make a recursive call with y decremented by 1.

To know more about the implementation, please refer to Product of 2 Numbers using Recursion.

Comment