The Wayback Machine - https://web.archive.org/web/20240930183246/https://www.geeksforgeeks.org/multiply-two-polynomials-2/
Open In App

Multiply two polynomials

Last Updated : 16 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
63.38%
10.1K

Given two polynomials represented by two arrays, write a function that multiplies given two polynomials. 

Example: 

Input:  A[] = {5, 0, 10, 6} 
        B[] = {1, 2, 4} 
Output: prod[] = {5, 10, 30, 26, 52, 24}

The first input array represents "5 + 0x^1 + 10x^2 + 6x^3"
The second array represents "1 + 2x^1 + 4x^2" 
And Output is "5 + 10x^1 + 30x^2 + 26x^3 + 52x^4 + 24x^5"
Recommended Practice

A simple solution is to one by one consider every term of the first polynomial and multiply it with every term of the second polynomial. Following is the algorithm of this simple method. 

multiply(A[0..m-1], B[0..n-1])
1) Create a product array prod[] of size m+n-1.
2) Initialize all entries in prod[] as 0.
3) Traverse array A[] and do following for every element A[i]
...(3.a) Traverse array B[] and do following for every element B[j]
          prod[i+j] = prod[i+j] + A[i] * B[j]
4) Return prod[].

The following is the implementation of the above algorithm. 

C++




// Simple C++ program to multiply two polynomials
#include <iostream>
using namespace std;
  
// A[] represents coefficients of first polynomial
// B[] represents coefficients of second polynomial
// m and n are sizes of A[] and B[] respectively
int *multiply(int A[], int B[], int m, int n)
{
   int *prod = new int[m+n-1];
  
   // Initialize the product polynomial
   for (int i = 0; i<m+n-1; i++)
     prod[i] = 0;
  
   // Multiply two polynomials term by term
  
   // Take ever term of first polynomial
   for (int i=0; i<m; i++)
   {
     // Multiply the current term of first polynomial
     // with every term of second polynomial.
     for (int j=0; j<n; j++)
         prod[i+j] += A[i]*B[j];
   }
  
   return prod;
}
  
// A utility function to print a polynomial
void printPoly(int poly[], int n)
{
    for (int i=0; i<n; i++)
    {
       cout << poly[i];
       if (i != 0)
        cout << "x^" << i ;
       if (i != n-1)
       cout << " + ";
    }
}
  
// Driver program to test above functions
int main()
{
    // The following array represents polynomial 5 + 10x^2 + 6x^3
    int A[] = {5, 0, 10, 6};
  
    // The following array represents polynomial 1 + 2x + 4x^2
    int B[] = {1, 2, 4};
    int m = sizeof(A)/sizeof(A[0]);
    int n = sizeof(B)/sizeof(B[0]);
  
    cout << "First polynomial is ";
    printPoly(A, m);
    cout <<endl<< "Second polynomial is ";
    printPoly(B, n);
  
    int *prod = multiply(A, B, m, n);
  
    cout <<endl<< "Product polynomial is ";
    printPoly(prod, m+n-1);
  
    return 0;
}


Java




// Java program to multiply two polynomials
class GFG
{
  
    // A[] represents coefficients 
    // of first polynomial
    // B[] represents coefficients 
    // of second polynomial
    // m and n are sizes of A[] and B[] respectively
    static int[] multiply(int A[], int B[], 
                            int m, int n) 
    {
        int[] prod = new int[m + n - 1];
  
        // Initialize the product polynomial
        for (int i = 0; i < m + n - 1; i++) 
        {
            prod[i] = 0;
        }
  
        // Multiply two polynomials term by term
        // Take ever term of first polynomial
        for (int i = 0; i < m; i++) 
        {
            // Multiply the current term of first polynomial
            // with every term of second polynomial.
            for (int j = 0; j < n; j++) 
            {
                prod[i + j] += A[i] * B[j];
            }
        }
  
        return prod;
    }
  
    // A utility function to print a polynomial
    static void printPoly(int poly[], int n) 
    {
        for (int i = 0; i < n; i++) 
        {
            System.out.print(poly[i]);
            if (i != 0) 
            {
                System.out.print("x^" + i);
            }
            if (i != n - 1) 
            {
                System.out.print(" + ");
            }
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        // The following array represents 
        // polynomial 5 + 10x^2 + 6x^3
        int A[] = {5, 0, 10, 6};
  
        // The following array represents 
        // polynomial 1 + 2x + 4x^2
        int B[] = {1, 2, 4};
        int m = A.length;
        int n = B.length;
  
        System.out.println("First polynomial is n");
        printPoly(A, m);
        System.out.println("nSecond polynomial is n");
        printPoly(B, n);
  
        int[] prod = multiply(A, B, m, n);
  
        System.out.println("nProduct polynomial is n");
        printPoly(prod, m + n - 1);
    }
}
  
// This code contributed by Rajput-Ji


Python3




# Simple Python3 program to multiply two polynomials
  
# A[] represents coefficients of first polynomial
# B[] represents coefficients of second polynomial
# m and n are sizes of A[] and B[] respectively
def multiply(A, B, m, n):
  
    prod = [0] * (m + n - 1);
      
    # Multiply two polynomials term by term
      
    # Take ever term of first polynomial
    for i in range(m):
          
        # Multiply the current term of first 
        # polynomial with every term of 
        # second polynomial.
        for j in range(n):
            prod[i + j] += A[i] * B[j];
  
    return prod;
  
# A utility function to print a polynomial
def printPoly(poly, n):
  
    for i in range(n):
        print(poly[i], end = "");
        if (i != 0):
            print("x^", i, end = "");
        if (i != n - 1):
            print(" + ", end = "");
  
# Driver Code
  
# The following array represents
# polynomial 5 + 10x^2 + 6x^3
A = [5, 0, 10, 6];
  
# The following array represents 
# polynomial 1 + 2x + 4x^2
B = [1, 2, 4];
m = len(A);
n = len(B);
  
print("First polynomial is ");
printPoly(A, m);
print("\nSecond polynomial is ");
printPoly(B, n);
  
prod = multiply(A, B, m, n);
  
print("\nProduct polynomial is ");
printPoly(prod, m+n-1);
  
# This code is contributed by chandan_jnu


C#




// C# program to multiply two polynomials
using System;
  
class GFG 
{
  
    // A[] represents coefficients 
    // of first polynomial
    // B[] represents coefficients 
    // of second polynomial
    // m and n are sizes of A[] 
    // and B[] respectively
    static int[] multiply(int []A, int []B, 
                            int m, int n) 
    {
        int[] prod = new int[m + n - 1];
  
        // Initialize the product polynomial
        for (int i = 0; i < m + n - 1; i++) 
        {
            prod[i] = 0;
        }
  
        // Multiply two polynomials term by term
        // Take ever term of first polynomial
        for (int i = 0; i < m; i++)
        {
            // Multiply the current term of first polynomial
            // with every term of second polynomial.
            for (int j = 0; j < n; j++) 
            {
                prod[i + j] += A[i] * B[j];
            }
        }
  
        return prod;
    }
  
    // A utility function to print a polynomial
    static void printPoly(int []poly, int n)
    {
        for (int i = 0; i < n; i++) {
            Console.Write(poly[i]);
            if (i != 0) {
                Console.Write("x^" + i);
            }
            if (i != n - 1) {
                Console.Write(" + ");
            }
        }
    }
  
    // Driver code
    public static void Main(String[] args)
    {
          
        // The following array represents 
        // polynomial 5 + 10x^2 + 6x^3
        int []A = {5, 0, 10, 6};
  
        // The following array represents
        // polynomial 1 + 2x + 4x^2
        int []B = {1, 2, 4};
        int m = A.Length;
        int n = B.Length;
  
        Console.WriteLine("First polynomial is n");
        printPoly(A, m);
        Console.WriteLine("nSecond polynomial is n");
        printPoly(B, n);
  
        int[] prod = multiply(A, B, m, n);
  
        Console.WriteLine("nProduct polynomial is n");
        printPoly(prod, m + n - 1);
    }
}
  
// This code has been contributed by 29AjayKumar 


PHP




<?php
// Simple PHP program to multiply two polynomials
  
// A[] represents coefficients of first polynomial
// B[] represents coefficients of second polynomial
// m and n are sizes of A[] and B[] respectively
function multiply($A, $B, $m, $n)
{
    $prod = array_fill(0, $m + $n - 1, 0);
      
    // Multiply two polynomials term by term
      
    // Take ever term of first polynomial
    for ($i = 0; $i < $m; $i++)
    {
        // Multiply the current term of first 
        // polynomial with every term of 
        // second polynomial.
        for ($j = 0; $j < $n; $j++)
            $prod[$i + $j] += $A[$i] * $B[$j];
    }
  
    return $prod;
}
  
// A utility function to print a polynomial
function printPoly($poly, $n)
{
    for ($i = 0; $i < $n; $i++)
    {
        echo $poly[$i];
        if ($i != 0)
            echo "x^" . $i;
        if ($i != $n - 1)
        echo " + ";
    }
}
  
// Driver Code
  
// The following array represents
// polynomial 5 + 10x^2 + 6x^3
$A = array(5, 0, 10, 6);
  
// The following array represents 
// polynomial 1 + 2x + 4x^2
$B = array(1, 2, 4);
$m = count($A);
$n = count($B);
  
echo "First polynomial is \n";
printPoly($A, $m);
echo "\nSecond polynomial is \n";
printPoly($B, $n);
  
$prod = multiply($A, $B, $m, $n);
  
echo "\nProduct polynomial is \n";
printPoly($prod, $m+$n-1);
  
// This code is contributed by chandan_jnu
?>


Javascript




<script>
  
// Simple JavaScript program to multiply two polynomials
  
  // A[] represents coefficients of first polynomial
  // B[] represents coefficients of second polynomial
  // m and n are sizes of A[] and B[] respectively
    function multiply(A, B, m, n){
      var prod = [];
      for (var i = 0; i < m + n - 1; i++) prod[i] = 0;
      // Multiply two polynomials term by term
  
      // Take ever term of first polynomial
      for(var i = 0; i < m ; i++){
          // Multiply the current term of first 
          // polynomial with every term of 
          // second polynomial.
          for (var j = 0; j < n ; j++)
              prod[i + j] += A[i] * B[j];
      }
      return prod;
  }
  // A utility function to print a polynomial
  function printPoly(poly, n){
      let ans= '';
      for (var i = 0; i < n ; i++){
          ans += poly[i];
          if (i != 0)
              ans +="x^ "+i;
          if (i != n - 1)
              ans += " + ";
      }
      document.write(ans)
  }
  
  // Driver Code
  
  // The following array represents
  // polynomial 5 + 10x^2 + 6x^3
  A = [5, 0, 10, 6];
  
  // The following array represents 
  // polynomial 1 + 2x + 4x^2
  let B = [1, 2, 4];
  let m = (A).length;
  let n = (B).length;
  
  document.write("First polynomial is " + "<br>");
  printPoly(A, m);
  document.write("<br>");
  document.write("Second polynomial is " + "<br>");
  printPoly(B, n);
  
  let prod = multiply(A, B, m, n);
  document.write("<br>");
  document.write("Product polynomial is " + "<br>");
  printPoly(prod, m+n-1);
    
</script>


Output

First polynomial is 5 + 0x^1 + 10x^2 + 6x^3
Second polynomial is 1 + 2x^1 + 4x^2
Product polynomial is 5 + 10x^1 + 30x^2 + 26x^3 + 52x^4 + 24x^5

The time complexity of the above solution is O(mn). If the size of two polynomials same, then the time complexity is O(n2).

Auxiliary Space: O(m + n)

Can we do better? 
There are methods to do multiplication faster than O(n2) time. These methods are mainly based on divide and conquer. Following is one simple method that divides the given polynomial (of degree n) into two polynomials one containing lower degree terms(lower than n/2) and the other containing higher degree terms (higher than or equal to n/2) 

Let the two given polynomials be A and B.  
For simplicity, Let us assume that the given two polynomials are of
same degree and have degree in powers of 2, i.e., n = 2i

The polynomial 'A' can be written as A0 + A1*xn/2
The polynomial 'B' can be written as B0 + B1*xn/2

For example 1 + 10x + 6x2 - 4x3 + 5x4 can be
written as (1 + 10x) + (6 - 4x + 5x2)*x2

A * B  = (A0 + A1*xn/2) * (B0 + B1*xn/2)
       = A0*B0 + A0*B1*xn/2 + A1*B0*xn/2 + A1*B1*xn
       = A0*B0 + (A0*B1 + A1*B0)xn/2 + A1*B1*xn  

So the above divide and conquer approach requires 4 multiplications and O(n) time to add all 4 results. Therefore the time complexity is T(n) = 4T(n/2) + O(n). The solution of the recurrence is O(n2) which is the same as the above simple solution.
The idea is to reduce the number of multiplications to 3 and make the recurrence as T(n) = 3T(n/2) + O(n) 

How to reduce the number of multiplications? 
This requires a little trick similar to Strassen’s Matrix Multiplication. We do the following 3 multiplications. 

X = (A0 + A1)*(B0 + B1) // First Multiplication
Y = A0B0  // Second 
Z = A1B1  // Third

The missing middle term in above multiplication equation A0*B0 + (A0*B1 + 
A1*B0)xn/2 + A1*B1*xn can obtained using below.
A0B1 + A1B0 = X - Y - Z  

In-Depth Explanation 
Conventional polynomial multiplication uses 4 coefficient multiplications: 

(ax + b)(cx + d) = acx2 + (ad + bc)x + bd

However, notice the following relation:

(a + b)(c + d) = ad + bc + ac + bd

The rest of the two components are exactly the middle coefficient for the product of two polynomials. Therefore, the product can be computed as:

(ax + b)(cx + d) = acx2 + 
((a + b)(c + d) - ac - bd )x + bd

Hence, the latter expression has only three multiplications.
So the time taken by this algorithm is T(n) = 3T(n/2) + O(n) 
The solution of the above recurrence is O(nLg3) which is better than O(n2).
We will soon be discussing the implementation of the above approach. 
There is an O(nLogn) algorithm also that uses Fast Fourier Transform to multiply two polynomials (Refer to this and this for details)



Previous Article
Next Article

Similar Reads

Polynomials in One Variable | Polynomials Class 9 Maths
Polynomials in One Variable: Polynomial word originated from two words “poly” which means “many” and the word “nominal” which means “term”. In maths, a polynomial expression consists of variables known as indeterminate and coefficients. Polynomials are expressions with one or more terms with a non-zero coefficient. A polynomial can have more than o
7 min read
Multiplication of two polynomials using Linked list
Given two polynomials in the form of linked list. The task is to find the multiplication of both polynomials. Examples: Input: Poly1: 3x^2 + 5x^1 + 6, Poly2: 6x^1 + 8 Output: 18x^3 + 54x^2 + 76x^1 + 48 On multiplying each element of 1st polynomial with elements of 2nd polynomial, we get 18x^3 + 24x^2 + 30x^2 + 40x^1 + 36x^1 + 48 On adding values wi
15 min read
Adding two polynomials using Circular Linked List
Given two polynomial numbers represented by a circular linked list, the task is to add these two polynomials by adding the coefficients of the powers of the same variable. Note: In given polynomials, the term containing the higher power of x will come first. Examples: Input: 1st Number = 5x^2 * y^1 + 4x^1 * y^2 + 3x^1 * y^1 + 2x^1 2nd Number = 3x^1
12 min read
Adding two polynomials using Linked List using map
Given two polynomial numbers represented by a linked list. Write a function to perform their algebraic sum. Examples: Input: 1st number = 5x^2 + 4x^1 + 2x^0 2nd number = 5x^1 + 5x^0 Output: 5x^2 + 9x^1 + 7x^0 Approach: The implementation uses map data structure so that all coefficients of same power value are added together and kept in key-value pa
10 min read
Program to add two polynomials
Given two polynomials represented by two arrays, write a function that adds given two polynomials. Example: Input: A[] = {5, 0, 10, 6} B[] = {1, 2, 4} Output: sum[] = {6, 2, 14, 6} The first input array represents "5 + 0x^1 + 10x^2 + 6x^3" The second array represents "1 + 2x^1 + 4x^2" And Output is "6 + 2x^1 + 14x^2 + 6x^3" We strongly recommend mi
15+ min read
Adding two polynomials using Linked List
Given two polynomial numbers represented by a linked list. The task is to add these lists meaning the coefficients with the same variable powers will be added.Note: Given polynomials are sorted in decreasing order of power. Example: Input: head1: [[5, 2], [4, 1], [2, 0]]head2: [[5, 1], [5, 0]]Output: [[5, 2], [9, 1], [7, 0]]Explanation: Input: head
15+ min read
Multiply two integers without using multiplication, division and bitwise operators, and no loops
By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. Approach: Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times. Base case: When the numbers of times x has to be added becomes 0. Recurs
9 min read
Multiply two numbers represented as linked lists into a third list
Given two numbers represented by linked lists, write a function that returns the head of the new linked list that represents the number that is the product of those numbers. Examples: Input : 9->4->6 8->4 Output : 7->9->4->6->4 Input : 9->9->9->4->6->9 9->9->8->4->9 Output : 9->9->7->9->5-
15+ min read
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 = 16Output:1EExplanation: NX * MY = (101)2 * (110)2 = (11110)2(11110)2 = (1E)16 Input: N = 101, M = A, X = 2, Y = 20, P = 16Output: 32Explanation: Nx = (101)2
10 min read
Program to multiply two Matrix by taking data from user
Given two matrices, the task is to multiply them. The size and number of elements of matrices are to be read from the keyboard. Examples: Input: row1 = 2, col1 = 2, mat1[][] = {{1, 2}, {3, 4}}, row2 = 2, col2 = 2, mat2[][] = {{1, 1}, {1, 1}} Output: {{3, 3}, {7, 7}} Input: row1 = 2, col1 = 2, mat1[][] = {{2, 4}, {3, 4}} row1 = 2, col1 = 2, mat2[][]
15 min read
Russian Peasant (Multiply two numbers using bitwise operators)
Given two integers, write a function to multiply them without using multiplication operator.There are many other ways to multiply two numbers (For example, see this). One interesting method is the Russian peasant algorithm. The idea is to double the first number and halve the second number repeatedly till the second number doesn't become 1. In the
5 min read
Program to multiply two matrices
Given two matrices, the task is to multiply them. Matrices can either be square or rectangular: Examples:  (Square Matrix Multiplication) Input: mat1[m][n] = { {1, 1}, {2, 2} }mat2[n][p] = { {1, 1}, {2, 2} }Output: result[m][p] = { {3, 3}, {6, 6} } (Rectangular Matrix Multiplication) Input: mat1[3][2] = { {1, 1}, {2, 2}, {3, 3} }mat2[2][3] = { {1,
14 min read
Javascript Program to multiply two matrices
Given two matrices, the task to multiply them. Matrices can either be square or rectangular. Example:  Input : mat1[][] = {{2, 4}, {1, 4}} mat2[][] = {{1, 4}, {1, 3}} Output : {{6, 16}, {7, 18}} Multiplication of Square Matrices : The below program multiplies two square matrices of size 4*4, we can change N for different dimensions. [GFGTABS] JavaS
3 min read
Javascript Program To Multiply Two Numbers Represented By Linked Lists
Given two numbers represented by linked lists, write a function that returns the multiplication of these two linked lists. Examples: Input: 9->4->6 8->4Output: 79464Input: 3->2->1 1->2Output: 3852Solution: Traverse both lists and generate the required numbers to be multiplied and then return the multiplied values of the two number
2 min read
Multiply two numbers represented by Linked Lists
Given two numbers represented by linked lists, The task is to return the multiplication of these two linked lists. Examples: Input : head1 : 1->0->0 , head2 : 1->0Output: 1000Explanation: head1 represents 100 and head2 represents the number 10, 100 x 10 = 1000 Input : head1 : 3->2, head2 : 2Output: 64Explanation: head1 represents 32 and
7 min read
Factoring Polynomials
Factoring Polynomials: A basic algebraic concept called factoring polynomials involves breaking down a polynomial equation into simpler parts. Factoring can be used to solve equations, simplify complicated expressions, and locate the roots or zeros of polynomial functions.  In several fields of mathematics, including engineering, physics, and compu
9 min read
Types of Polynomials (Based on Terms and Degrees)
Types of Polynomials: In mathematics, an algebraic expression is an expression built up from integer constants, variables, and algebraic operations. There are mainly four types of polynomials based on degree-constant polynomial (zero degree), linear polynomial ( 1st degree), quadratic polynomial (2nd degree), and cubic polynomial (3rd degree). Ther
9 min read
Factorization of Polynomials Practice Problems
Factoring polynomials is a fundamental skill in algebra that involves breaking down a polynomial into simpler factors that, when multiplied together, give the original polynomial. This process is crucial for solving polynomial equations, simplifying expressions, and understanding polynomial functions. The practice problems for factoring polynomials
11 min read
Class 10 RD Sharma Solutions- Chapter 2 Polynomials - Exercise 2.1 | Set 2
In this section, we delve into Chapter 2 of the Class 10 RD Sharma textbook, focusing on Polynomials. Exercise 2.1 is designed to help students understand the fundamental concepts of polynomials, including their types, properties, and various operations performed on them. Class 10 RD Sharma Solutions - Chapter 2 Polynomials - Exercise 2.1 | Set 2Th
14 min read
Class 9 RD Sharma Solutions - Chapter 6 Factorisation of Polynomials- Exercise 6.5 | Set 1
In Class 9 mathematics, understanding the factorization of polynomials is crucial as it forms the foundation for the more advanced algebraic concepts. Chapter 6 of RD Sharma's textbook focuses on the various methods of factorizing polynomials helping the students simplify complex expressions and solve equations effectively. Exercise 6.5 in this cha
13 min read
Class 9 RD Sharma Solutions - Chapter 6 Factorisation of Polynomials- Exercise 6.5 | Set 2
Factorisation is a key concept in algebra especially important for simplifying polynomial expressions. It involves breaking down a polynomial into a product of the simpler polynomials or factors. This process is crucial for solving polynomial equations and understanding polynomial functions in various mathematical contexts. Chapter 6 of RD Sharma’s
9 min read
Efficient way to multiply with 7
Given a number n, find the result after multiplying it by 7. Example: Input: n=8Output: 56 Naive Approach: The basic way to solve this is to use a multiplication operator, add the number 7 times or use recursive function. C/C++ Code #include <bits/stdc++.h> using namespace std; // c++ implementation long multiplyBySeven(long n) { return (n *
6 min read
Multiply any Number with 4 using Bitwise Operator
We are a Number n and our task is to multiply the number by 4 using a bit-wise Operator. Examples: Input : 4 Output :16 Input :5 Output :20 Explanation Case 1:- n=4 the binary of 4 is 100 and now shifts two bit right then 10000 now the number is 16 is multiplied 4*4=16 ans. Approach :- (n<<2) shift two bit right C/C++ Code // C++ program to m
3 min read
Multiply the given number by 2 such that it is divisible by 10
Given a number, the only operation allowed is to multiply the number by 2. Calculate the minimum number of operations to make the number divisible by 10.NOTE: If it is not possible to convert then print -1. Examples: Input: 10 Output: 0 As the given number is itself divisible by 10, the answer is 0. Input: 1 Output: -1 As by multiplying with 2, giv
7 min read
Multiply a number by 15 without using * and / operators
Given a integer N, the task is to multiply the number with 15 without using multiplication * and division / operators. Examples: Input: N = 10 Output: 150 Input: N = 7 Output: 105 Method 1: We can multiply integer N by 15 using bitwise operators. First left shift the number by 4 bits which is equal to (16 * N) then subtract the original number N fr
6 min read
Queries to multiply the given subarray with given number X and print sum
Given an array arr[] and Q queries where each query contains three integers (l, r, x), the task is to print the sum of the elements in range [l,r] after multiplying each element with x. Query(l, r, x) = arr[l]*x + arr[l+1]*x + .... arr[r-1]*x + arr[r]*x Note: Multiplication with x is done to calculate the answer and it is not updated in the input a
7 min read
Multiply perfect number
A number N is said to be Multiply-perfect numbers if N divides sigma(N), where sigma(N) = sum of all divisors of N.The first few Multiply-perfect numbers are: 1, 6, 28, 120, 496, 672, ........ Check if N is a Multiply-perfect number Given a number N, the task is to find if this number is Multiply-perfect number or not. Examples: Input: N = 120 Outp
5 min read
Multiply a single digit number in place to a number represented as a Linked List
Given a linked list of N nodes where each node represents digits of a number and a single-digit number M, the task is to multiply the list by M in-place and print the resulting linked list. Examples: Input: Linked list: 1 ? 2 ? 7 ? 3 ? NULL, M = 3Output: 3 ? 8 ? 1 ? 9 ? NULLExplanation: The given linked list represents the number 1273. Multiplying
12 min read
Find sequence of operations to convert 1 to N using Multiply-by-2-Add-1 or Subtract-1
Given an integer N, the task is to find a sequence of operations to convert 1 to N. You can perform any number of operations, and the goal is to reach the number N using these operations. If it's not possible to reach N, return -1. There are two possible operations that can be performed on the current number M: Multiply M by 2 and subtract 1 from i
6 min read
Minimize multiply by position so that Array product is divisible by 2^K
Given an array nums [] of size N containing positive integers and a positive integer K, the task is to find the minimum number of operations such that the array product is divisible by 2K where in each operation nums[i] is multiplied by its position (i.e. i+1). Note: Return -1 if it is not possible to make the array product divisible 2K. Examples:
11 min read