An evil number is a nonnegative integer whose binary form has an even number of 1 bits. That count is called the popcount (Hamming weight). An odd popcount means the number is odious.
Remember
n is evil ↔ (count of 1-bits in binary n) is even
Examples:
15 → 1111 → 4 ones → evil
7 → 111 → 3 ones → odious
0 → 0 → 0 ones → evil
3 → 11 → 2 ones → evil
n
Binary
Ones
Result
0
0
0
Evil
3
11
2
Evil
7
111
3
Odious
15
1111
4
Evil
Approach
How to Check an Evil Number in C++
Four clear steps — then pick a teaching loop or the built-in popcount.
Require n >= 0 (this page rejects negatives).
Count how many 1 bits appear in binary n.
If that count is even, n is evil; otherwise it is odious.
Use a divide-by-2 loop to learn the idea, or std::popcount (C++20) for production code.
Method
Idea
Time
Best for
Divide by 2
Read bits with % 2 / / 2
O(bits)
Interviews, teaching binary
std::popcount
Built-in popcount, then % 2
O(1)
Clear modern C++
Pseudocode
Pseudocode
function IsEvil(n):
if n < 0:
return false
ones = 0
while n > 0:
if (n mod 2) == 1:
ones = ones + 1
n = n / 2
return (ones mod 2) == 0
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Goal
Even count of binary 1 bits
Opposite
Odd popcount → odious
Zero
Evil (0 ones is even)
Fast check
std::popcount((unsigned)n) % 2 == 0
Header
<bit> (C++20)
Classic evil
0, 3, 5, 6, 9, 10, 15
Classic odious
1, 2, 4, 7, 8
Try it
Live Preview
Enter a nonnegative integer to see its binary form, popcount, and verdict.
Nonnegative whole numbers only. Tap a chip or type a value.
Result
n = 15
Binary = 1111
Ones = 4 (even)
Verdict: EVIL NUMBER
Trace
Worked Walkthrough — n = 15
Peel bits with % 2, count the ones, then check parity.
Calculation
15 in binary = 1111
Step 1: 15 % 2 = 1 → ones = 1; n = 7
Step 2: 7 % 2 = 1 → ones = 2; n = 3
Step 3: 3 % 2 = 1 → ones = 3; n = 1
Step 4: 1 % 2 = 1 → ones = 4; n = 0
ones = 4 → even → 15 is evil
Code
C++ Programs
Start with the divide-by-2 loop so you can show each bit. Then use std::popcount when you want a short modern check.
Example 1 — Divide-by-2 Loop
Read each bit with % 2, count the ones, then test whether that count is even.
C++
#include <iostream>
using namespace std;
bool IsEvil(int n)
{
if (n < 0)
{
return false;
}
int ones = 0;
while (n > 0)
{
if (n % 2 == 1)
{
ones++;
}
n /= 2;
}
return ones % 2 == 0;
}
int main()
{
int number = 15;
if (IsEvil(number))
{
cout << number << " is an Evil Number." << endl;
}
else
{
cout << number << " is not an Evil Number." << endl;
}
return 0;
}
Output
15 is an Evil Number.
How It Works
Reject negatives so the definition stays on nonnegative integers.
n % 2 is the least significant bit; if it is 1, increment ones.
n /= 2 shifts the remaining bits right (integer division).