

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find value of y mod (2 raised to power x) in C++
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
- Related Questions & Answers
- Check if a number can be expressed as x^y (x raised to power y) in C++
- Find maximum among x^(y^2) or y^(x^2) where x and y are given in C++
- Find the value of the function Y = (X^6 + X^2 + 9894845) % 981 in C++
- Find power of power under mod of a prime in C++
- Number of digits in 2 raised to power n in C++
- Find multiple of x closest to or a ^ b (a raised to power b) in C++
- Find larger of x^y and y^x in C++
- Find x, y, z that satisfy 2/n = 1/x + 1/y + 1/z in C++
- Program to find out the value of a power of 2 in Python
- Count number of solutions of x^2 = 1 (mod p) in given range in C++
- Program to find value of find(x, y) is even or odd in Python
- Find number of pairs (x, y) in an array such that x^y > y^x in C++
- Program to find Reordered Power of 2 in Python
- Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++
- Find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n in C++
Advertisements