Round up to nearest power of 2 in C++
In this tutorial, we will learn how to round off a given number to the nearest power of 2 in C++.
For example,
Input: n= 19
Output: 16
There can be two cases. The power of 2 can be either less or greater than the given number. The program should be such that the number should be rounded to the nearest power of 2.
Let’s understand this with the help of code:
#include <iostream> #include <cmath> using namespace std; int PowerOf2(int n) { if (n <= 0) { return 0; } int nextPowerOf2 = pow(2,ceil(log2(n))); // Calculating the next power of 2 greater than n int prevPowerOf2 = pow(2,floor(log2(n))); // Calculating the next power of 2 less than n int diff1 = nextPowerOf2 - n; // Check which power of 2 is closest to n int diff2 = n - prevPowerOf2; if (diff1 <= diff2) { return nextPowerOf2; } else { return prevPowerOf2; } } int main() { int n = 19; int powerOf2 = PowerOf2(n); cout << powerOf2; return 0; }
Output: 16
In this code, if n is less than or equal to zero, then we return 0 there is no power of 2 less than or greater than 0. The ceil function from the cmath
library calculates the smallest integer value greater than or equal to the base-2 logarithm of n. The pow() function calculates the value of 2 raised to the value generated by ceil function. It rounds up n to the next power of 2.
Similarly, the previous power of 2 less than n is calculated by 2 raised to the floor of the base-2 logarithm of n. The floor function rounds down to the nearest integer.
Then we calculate diff1 and diff2 as diff1 = nextPowerOf2 – n and diff2 = n – prevPowerOf2.If diff1<=diff2 we return the nextPowerOf2, otherwise we return prevPowerOf2.
Leave a Reply