Find value of y mod (2 raised to power x) in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two values x and y. Our task is to find value of y mod (2 raised to power x).

Let's take an example to understand the problem,

Input : x = 2, y = 19
Output : 3

Explanation

y % 2x = 19 % 22 = 19 % 4 = 3

Solution Approach

A simple solution to the problem is by directly calculating the value of 2x using the pow() function and then finding the value of y % 2x.

Another approach to solve the problem is by using log. For the value of y < 2x, remainder is y. For this case we have

Log2y < x

Also, the maximum value of x can be 63 which will have the value overflow for y. Hence, mod is equal to x.

Taking all these under consideration, we have these three cases −

if(log y < x) -> return y
else if(x > 63) -> return y
else -> return (y % pow(2, x))

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
long long int findModVal(long long int y, int x){
   if (log2(y) < x)
      return y;
   if (x > 63)
      return y;
   return (y % (1 << x));
}
int main(){
   long long int y = 82829;
   int x = 12;
   cout<<"The value of y mod 2^x is "<<findModVal(y, x);
   return 0;
}

Output

The value of y mod 2^x is 909
raja
Updated on 01-Feb-2022 08:00:18

Advertisements