
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check if a number is power of 8 or not in C++
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
#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
- Related Articles
- Check if a large number is divisible by 8 or not in C++
- Check if a number is jumbled or not in C++
- Check if a number is a Krishnamurthy Number or not in C++
- Check if a number is an Unusual Number or not in C++
- Check if a number is an Achilles number or not in C++
- Check if a number is a power of another number in C++
- Check if a given number is sparse or not in C++
- Check if a number is Quartan Prime or not in C++
- Check if a number is Primorial Prime or not in C++
- Program to check a number is power of two or not in Python
- Check if a number is a Pythagorean Prime or not in C++
- Check if a number is in given base or not in C++
- Check if a number is divisible by 23 or not in C++
- Check if a number is divisible by 41 or not in C++
- C# Program to check if a number is prime or not

Advertisements