Multiply two numbers of different base and represent product in another given base

Given two numbers N, M in the bases X, Y and another base P. The task is to find the product of N and M and represent the product in base P.
Examples:
Input: N = 101, M = 110, X = 2, Y = 2, P = 16
Output:1E
Explanation: NX * MY = Â (101)2 * (110)2Â = (11110)2
(11110)2 = (1E)16Input: Â N = 101, M = A, X = 2, Y = 20, P = 16
Output: Â 32
Explanation: Nx = (101)2 = (5)20Â Â
NX Â * Â MY = Â (5)20 * (A)20 Â = (2A)20
(2A)20 = (32)16
Approach: The approach is to convert the given numbers in decimal, perform the product and then turn it back to a number of base p. Follow the steps mentioned below:
- Convert NX and MY to decimal number.
- Perform multiplication on the decimal numbers.
- Convert the result of multiplication from decimal to base P.
Below is the implementation of the above approach.Â
C++
// C++ code for the above approach#include <bits/stdc++.h>using namespace std;Â
// Convert Number from a given base// to decimal// Return the value of a char.static int value(char c){  if (c >= '0' && c <= '9')    return (int)c - '0';  else    return (int)c - 'A' + 10;}Â
// Function to convert a// number from given base to decimalint toDecimal(string s, int base){Â Â int length = s.length();Â
  // Initialize power of base and result  int power = 1, ans = 0;Â
  // Decimal equivalent of s  for (int i = length - 1; i >= 0; i--)  {    ans += value(s[i]) * power;    power = power * base;  }Â
  return ans;}Â
// Function to convert decimal// to any given basechar reverseValue(int n){  if (n >= 0 && n <= 9)    return (char)(n + 48);  else    return (char)(n - 10 + 65);}Â
// Function to convert a given// decimal number to a base 'base'string toBase(int base, int num){Â Â string s = "";Â
  // Convert input number is given  // base by repeatedly dividing it  // by base and taking remainder  while (num > 0)  {    s += reverseValue(num % base);    num /= base;  }  string sb = "";Â
  // Append a string into StringBuilder  sb += (s);Â
  // Reverse the result  reverse(sb.begin(), sb.end());  return sb;}Â
// Function to find// the product of N and Mvoid findProduct(string N, int X,                 string M,                 int Y, int P){Â
  // Convert N to decimal  int decimalX = toDecimal(N, X);Â
  // Convert y to decimal  int decimalY = toDecimal(M, Y);Â
  // Multiply the decimal numbers  int product = decimalX * decimalY;Â
  // Convert product to base  string result = toBase(P, product);Â
  // Print the result  cout << (result);}Â
// Driver codeint main(){Â Â string N = "101", M = "110";Â Â int X = 2, Y = 2, P = 16;Â Â findProduct(N, X, M, Y, P);Â Â return 0;}Â
// This code is contributed by Potta Lokesh |
Java
// Java code to implement above approachimport java.io.*;Â
class GFG {         // Function to find     // the product of N and M    static void findProduct(String N, int X,                             String M,                            int Y, int P)    {Â
        // Convert N to decimal        int decimalX = toDecimal(N, X);Â
        // Convert y to decimal        int decimalY = toDecimal(M, Y);Â
        // Multiply the decimal numbers        int product = decimalX * decimalY;Â
        // Convert product to base        String result = toBase(P, product);Â
        // Print the result        System.out.println(result);    }Â
    // Convert Number from a given base     // to decimal    // Return the value of a char.    static int value(char c)    {        if (c >= '0' && c <= '9')            return (int)c - '0';        else            return (int)c - 'A' + 10;    }Â
    // Function to convert a    // number from given base to decimal    static int toDecimal(String s, int base)    {        int length = s.length();Â
        // Initialize power of base and result        int power = 1, ans = 0;Â
        // Decimal equivalent of s        for (int i = length - 1; i >= 0; i--) {            ans += value(s.charAt(i)) * power;            power = power * base;        }Â
        return ans;    }Â
    // Function to convert decimal     // to any given base    static char reverseValue(int n)    {        if (n >= 0 && n <= 9)            return (char)(n + 48);        else            return (char)(n - 10 + 65);    }Â
    // Function to convert a given     // decimal number to a base 'base'    static String toBase(int base, int num)    {        String s = "";Â
        // Convert input number is given        // base by repeatedly dividing it        // by base and taking remainder        while (num > 0) {            s += reverseValue(num % base);            num /= base;        }        StringBuilder sb = new StringBuilder();Â
        // Append a string into StringBuilder        sb.append(s);Â
        // Reverse the result        return new String(sb.reverse());    }         // Driver code    public static void main(String[] args)    {        String N = "101", M = "110";        int X = 2, Y = 2, P = 16;        findProduct(N, X, M, Y, P);    }} |
Python3
# Python code for the above approachÂ
# Convert Number from a given base# to decimal# Return the value of a char.def value(c):Â
  if (ord(c[0]) >= ord('0') and ord(c) <= ord('9')):    return int(c)  else:    return ord(c[0]) - ord('A') + 10Â
# Function to convert a# number from given base to decimaldef toDecimal(s,base):Â
  length = len(s)Â
  # Initialize power of base and result  power,ans = 1,0Â
  # Decimal equivalent of s  for i in range(length-1,-1,-1):Â
    ans += value(s[i]) * power    power = power * baseÂ
  return ansÂ
# Function to convert decimal# to any given basedef reverseValue(n):Â
  if (n >= 0 and n <= 9):    return chr(n + 48)  else:    return chr(n - 10 + 65)Â
# Function to convert a given# decimal number to a base 'base'def toBase(base, num):Â
  s = ""Â
  # Convert input number is given  # base by repeatedly dividing it  # by base and taking remainder  while (num > 0):Â
    s += reverseValue(num % base)    num = (num//base)Â
  sb = ""Â
  # Append a string into StringBuilder  sb += (s)Â
  # Reverse the result  sb = sb[::-1]  return sbÂ
# Function to find# the product of N and Mdef findProduct(N, X, M, Y, P):Â
  # Convert N to decimal  decimalX = toDecimal(N, X)Â
  # Convert y to decimal  decimalY = toDecimal(M, Y)Â
  # Multiply the decimal numbers  product = decimalX * decimalYÂ
  # Convert product to base  result = toBase(P, product)Â
  # Print the result  print(result)Â
# Driver codeN, M = "101", "110"X, Y, P = 2, 2, 16findProduct(N, X, M, Y, P)Â
# This code is contributed by shinjanpatra |
C#
// C# code to implement above approachusing System;class GFG{Â
  // Function to find   // the product of N and M  static void findProduct(String N, int X,                          String M,                          int Y, int P)  {Â
    // Convert N to decimal    int decimalX = toDecimal(N, X);Â
    // Convert y to decimal    int decimalY = toDecimal(M, Y);Â
    // Multiply the decimal numbers    int product = decimalX * decimalY;Â
    // Convert product to base    String result = toBase(P, product);Â
    // Print the result    Console.Write(result);  }Â
  // Convert Number from a given base   // to decimal  // Return the value of a char.  static int value(char c)  {    if (c >= '0' && c <= '9')      return (int)c - '0';    else      return (int)c - 'A' + 10;  }Â
  // Function to convert a  // number from given base to decimal  static int toDecimal(String s, int _base)  {    int length = s.Length;Â
    // Initialize power of base and result    int power = 1, ans = 0;Â
    // Decimal equivalent of s    for (int i = length - 1; i >= 0; i--)    {      ans += value(s[i]) * power;      power = power * _base;    }Â
    return ans;  }Â
  // Function to convert decimal   // to any given base  static char reverseValue(int n)  {    if (n >= 0 && n <= 9)      return (char)(n + 48);    else      return (char)(n - 10 + 65);  }Â
  // Function to convert a given   // decimal number to a base 'base'  static String toBase(int _base, int num)  {    String s = "";Â
    // Convert input number is given    // base by repeatedly dividing it    // by base and taking remainder    while (num > 0)    {      s += reverseValue(num % _base);      num /= _base;    }    String sb = "";Â
    // Append a string into StringBuilder    sb += s;Â
    // Reverse the result    char[] arr = sb.ToCharArray();    Array.Reverse(arr);    return new string(arr);  }Â
  // Driver code  public static void Main()  {    String N = "101", M = "110";    int X = 2, Y = 2, P = 16;    findProduct(N, X, M, Y, P);  }}Â
// This code is contributed by saurabh_jaiswal. |
Javascript
<script>Â
// JavaScript code for the above approachÂ
Â
// Convert Number from a given base// to decimal// Return the value of a char.function value(c){if (c.charCodeAt(0) >= '0'.charCodeAt(0) && c.charCodeAt(0) <= '9'.charCodeAt(0))    return parseInt(c);else    return c.charCodeAt(0) - 'A'.charCodeAt(0) + 10;}Â
// Function to convert a// number from given base to decimalfunction toDecimal(s,base){let length = s.length;Â
// Initialize power of base and resultlet power = 1, ans = 0;Â
// Decimal equivalent of sfor (let i = length - 1; i >= 0; i--){Â Â Â Â ans += value(s[i]) * power;Â Â Â Â power = power * base;}Â
return ans;}Â
// Function to convert decimal// to any given basefunction reverseValue(n){if (n >= 0 && n <= 9)    return String.fromCharCode(n + 48);else    return String.fromCharCode(n - 10 + 65);}Â
// Function to convert a given// decimal number to a base 'base'function toBase(base, num){let s = "";Â
// Convert input number is given// base by repeatedly dividing it// by base and taking remainderwhile (num > 0){Â Â Â Â s += reverseValue(num % base);Â Â Â Â num = Math.floor(num/base);}let sb = "";Â
// Append a string into StringBuildersb += (s);Â
// Reverse the resultsb = sb.split("").reverse().join("");return sb;}Â
// Function to find// the product of N and Mfunction findProduct(N, X, M, Y, P){Â
// Convert N to decimallet decimalX = toDecimal(N, X);Â
// Convert y to decimallet decimalY = toDecimal(M, Y);Â
// Multiply the decimal numberslet product = decimalX * decimalY;Â
// Convert product to baselet result = toBase(P, product);Â
// Print the resultdocument.write(result,"</br>");}Â
// Driver codeÂ
let N = "101", M = "110";let X = 2, Y = 2, P = 16;findProduct(N, X, M, Y, P);Â
// This code is contributed by shinjanpatraÂ
</script> |
Â
Â
1E
Â
Time Complexity: O(D) where D is the maximum number of digits in N, M and product
Auxiliary Space: O(1)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



