Program to find the product of a number with a Mersenne Number
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: 60
Input: 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++
#include <bits/stdc++.h>
using namespace std;
long multiplyByMersenne( long N, long M)
{
long x = log2(M + 1);
return ((N << x) - N);
}
int main()
{
long N = 4;
long M = 15;
cout << multiplyByMersenne(N, M);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static long multiplyByMersenne( long N, long M)
{
long x = ( int )(Math.log(M + 1 ) / Math.log( 2 ));
return ((N << x) - N);
}
public static void main(String[] args)
{
long N = 4 ;
long M = 15 ;
System.out.print(multiplyByMersenne(N, M));
}
}
|
Python3
import math
def multiplyByMersenne(N, M) :
x = int (math.log2(M + 1 ))
return ((N << x) - N)
N = 4
M = 15
print (multiplyByMersenne(N, M))
|
C#
using System;
class GFG{
static int multiplyByMersenne( int N, int M)
{
int x = ( int )(Math.Log(M + 1) / Math.Log(2));
return ((N << x) - N);
}
static public void Main()
{
int N = 4;
int M = 15;
Console.Write(multiplyByMersenne(N, M));
}
}
|
Javascript
<script>
function multiplyByMersenne(N, M)
{
let x = (Math.log(M + 1) / Math.log(2));
return ((N << x) - N);
}
let N = 4;
let M = 15;
document.write(multiplyByMersenne(N, M));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
25 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...