C++ Odious Number Program
Definition
What Is an Odious Number?
An odious number is a nonnegative integer whose binary form has an odd number of 1 bits. That count is the popcount. An even popcount means the number is evil.
Remember
n is odious ↔ (count of 1-bits in binary n) is odd
Examples:
1 → 1 → 1 one → odious
2 → 10 → 1 one → odious
7 → 111 → 3 ones → odious
3 → 11 → 2 ones → evil Approach
How to Check an Odious Number
- Require
n >= 0. - Count the
1bits by testingn % 2and then dividing by 2. - If that count is odd,
nis odious. - On C++20 you can replace the loop with
std::popcountfrom<bit>.
Program
C++ Program
Read one nonnegative integer and print whether it is odious.
C++
#include <iostream>
bool isOdious(unsigned n) {
int ones = 0;
while (n > 0) {
ones += n % 2;
n /= 2;
}
return ones % 2 == 1;
}
int main() {
unsigned n;
std::cout << "Enter a nonnegative integer: ";
std::cin >> n;
if (isOdious(n))
std::cout << n << " is odious\n";
else
std::cout << n << " is evil\n";
return 0;
} Frequently Asked Questions
A nonnegative integer whose binary form has an odd number of 1 bits.
Evil. An evil number has an even popcount, including zero.
Yes. 1 in binary is 1, and one is odd.
No. Zero has zero 1-bits, and zero is even, so 0 is evil.
Odd looks at n % 2. Odious looks at whether the count of 1-bits is odd. 2 is even and odious.
Next: Even Number
Check value parity with n % 2, which is not the same as popcount parity.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
7 people found this page helpful
