# Check if a number is power of 8 or not in C++

C++Server Side ProgrammingProgramming

In this section, we will see, if a number is the power of 8 or not using some easier method. If a number like 4096 is there, then the program will return true, as this is the power of 8.

The trick is simple. we will calculate log8(num). If this is an integer, then n is the power of 8. Here we will use the tranc(n) function to find the closest integer of the double value.

## Example

Live Demo

#include <iostream>
#include <cmath>
using namespace std;
bool isPowerOfEight(int n) {
double val = log(n)/log(8); //get log n to the base 8
return (val - trunc(val) < 0.000001);
}
int main() {
int number = 4096;
if(isPowerOfEight(number)){
cout << number << " is power of 8";
} else {
cout << number << " is not power of 8";
}
}

## Output

4096 is power of 8
Published on 22-Oct-2019 06:31:36