
- 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 can be represented as sum of non zero powers of 2 in C++
Here we will see, if we can represent a number as sum of two non-zero powers of 2. So we will check the given number N can be represented as (2x + 2y) where x, y > 0. Suppose a number is 10, this can be represented as 23 + 21.
The approach is simple. There are two cases. If the number n is even, it can be represented as 2x. Where x > 0. Another case is that is N is odd, it can never be represented as sum of powers of 2. We cannot use power as 0, so we cannot get odd numbers. for all odd numbers LSb of its binary representation is 1
Example
#include <iostream> using namespace std; bool isSumofTwosPower(int n) { if((n & 1) == 0){ return true; } else { return false; } } int main() { int num = 86; if(isSumofTwosPower(num)){ cout << "Can be represented"; } else { cout << "Cannot be represented"; } }
Output
Can be represented
- Related Articles
- Check if a number can be represented as a sum of 2 triangular numbers in C++
- Check if N can be represented as sum of integers chosen from set {A, B} in Python
- Check if a number can be expressed as a sum of consecutive numbers in C++
- Check if a number can be written as sum of three consecutive integers in C++
- Check if a prime number can be expressed as sum of two Prime Numbers in Python
- Program to check n can be represented as sum of k primes or not in Python
- Check if a number can be expressed as 2^x + 2^y in C++
- Check if a number can be expressed as sum two abundant numbers in C++
- Check if a given number can be represented in given a no. of digits in any base in C++
- Count ways to express a number as sum of powers in C++
- Check if a number can be expressed as power in C++
- Count numbers which can be represented as sum of same parity primes in C++
- Check if a number can be expressed as a^b in C++
- Check if a number can be expressed as a^b in Python
- Program to check whether number is a sum of powers of three in Python

Advertisements