- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- Check if a number can be expressed as x^y (x raised to power y) 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 the value of$3 x^{2}-2 y^{2}$if x=-2 and y=2
- Find the value of the function Y = (X^6 + X^2 + 9894845) % 981 in C++
- If $x=1, y=2$ and $z=5$, find the value of $x^{2}+y^{2}+z^{2}$.
- Find the value of the following using suitable properties(a) ( (3 x+4 y)^{2} )(b) ( (0.2 x-0.3 y)^{2} )(c) ( (x+3)(x-5) )(d) ( left(x-y^{2}right)^{2} )
- Given $(x^{2}+y^{2})$=74 and xy =35, find the value of:a) x+yb) x-y
- Find maximum among x^(y^2) or y^(x^2) where x and y are given in C++
- Find the value using suitable identity$( x-y^2 )^2$
- Find the value of $36x^2 +49y^2-84xy$ if $x=2, y=-2$.
- Count number of solutions of x^2 = 1 (mod p) in given range in C++
- Find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n in C++
- Find the value of ( k ), if ( x=2, y=1 ) is a solution of the equation ( 2 x+3 y=k )

Advertisements