📜  程序查找带有梅森编号的编号的乘积

📅  最后修改于: 2021-04-18 02:32:12             🧑  作者: Mango

给定一个整数N和一个梅森数M ,任务是在不使用‘*’运算符的情况下打印其产品。
注意:梅森数字是那些小于2的幂的数字

例子:

方法:可以根据以下观察结果解决给定问题:

因此,具有任何数字N的任何梅森数字的乘积都可以表示为(N << log 2 (M + 1))– N。

下面是上述方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
 
// Function to find prodcut of a
// Mersenne number with another number
long 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 Code
int main()
{
    long N = 4;
    long M = 15;
 
    cout << multiplyByMersenne(N, M);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
class GFG
{
 
// Function to find prodcut of a
// Mersenne number with another number
static 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 Code
public 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 approach
import math
 
# Function to find prodcut of a
# Mersenne number with another number
def 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 Code
N = 4
M = 15
 
print(multiplyByMersenne(N, M))
 
# This code is contributed by sanjoy_62.


C#
// C# program for the above approach
using 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

时间复杂度: O(1)
辅助空间: O(1)