Given an integer N and a Mersenne number M, the task is to print their product without using the ‘*’ operator.
Note: Mersenne numbers are those numbers which are one less than a power of two.
Examples:
Input: N = 4, M = 15
Output: 60Input: N = 9, M = 31
Output: 279
Approach: The given problem can be solved based on the following observations:
Suppose M can be represented as 2X – 1, then the product of N with M can be represented as N · 2X – N.
Therefore, product of any Mersenne number with any number N can be represented as (N << log2(M+1)) – N.
Below is the implementation of the above approach:
C++
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std;// Function to find prodcut of a// Mersenne number with another numberlong multiplyByMersenne(long N, long M){ // Stores the power of // 2 of integer M + 1 long x = log2(M + 1); // Return the product return ((N << x) - N);}// Driver Codeint main(){ long N = 4; long M = 15; cout << multiplyByMersenne(N, M); return 0;} |
Java
// Java program to implement// the above approachimport java.io.*;import java.util.*;class GFG{// Function to find prodcut of a// Mersenne number with another numberstatic long multiplyByMersenne(long N, long M){ // Stores the power of // 2 of integer M + 1 long x = (int)(Math.log(M + 1) / Math.log(2)); // Return the product return ((N << x) - N);}// Driver Codepublic static void main(String[] args){ long N = 4; long M = 15; System.out.print(multiplyByMersenne(N, M));}}// This code is contributed by souravghosh0416. |
Python3
# Python3 program for the above approachimport math# Function to find prodcut of a# Mersenne number with another numberdef multiplyByMersenne(N, M) : # Stores the power of # 2 of integer M + 1 x = int(math.log2(M + 1)) # Return the product return ((N << x) - N)# Driver CodeN = 4M = 15print(multiplyByMersenne(N, M))# This code is contributed by sanjoy_62. |
C#
// C# program for the above approachusing System;class GFG{ // Function to find prodcut of a // Mersenne number with another number static int multiplyByMersenne(int N, int M) { // Stores the power of // 2 of integer M + 1 int x = (int)(Math.Log(M + 1) / Math.Log(2)); // Return the product return ((N << x) - N); } // Driver Code static public void Main() { int N = 4; int M = 15; Console.Write(multiplyByMersenne(N, M)); }}// This code is contributed by splevel62. |
60
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


