Check Evil Number in Python

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Popcount parity

What You’ll Learn

An evil number has an even count of 1 bits in binary; an odd count means odious. This tutorial covers Hamming weight, bit_count(), manual loops, a live preview, worked Python examples, edge cases, and complexity.

Definition

Even popcount

Even number of 1-bits → evil; odd → odious.

Classic 15

1111

Four ones (even) so 15 is evil.

bit_count()

Built-in

Fastest readable Python one-liner for popcount.

Zero Is Evil

0 ones

Zero has popcount 0, and 0 is even.

Live Preview

Try any n

See popcount and evil/odious instantly.

O(bits)

Single check

Kernighan can reduce work to O(popcount).

Introduction

Evil numbers are nonnegative integers whose binary form has an even number of 1 bits. If the count is odd, the number is called odious. Example: 15 is 1111 (four ones) → evil; 7 is 111 (three ones) → odious.

The count of 1-bits is the Hamming weight (popcount). Evil means even Hamming weight; odious means odd.

Why it matters?

It turns even/odd thinking into bit-level parity — a bridge from simple modulo checks to popcount and bit tricks.

Key Highlights

Even Ones

Only the parity of the 1-bit count matters.

Zero Counts

0 is evil (zero ones is even).

Odious Pair

Odd popcount means odious, not evil.

Nonnegative

This page scopes the definition to n ≥ 0.

In short: count the 1-bits; if that count is even, n is evil.

📝 Problem & Approach

Given a nonnegative integer n, decide whether its binary popcount is even.

python
# 15 → 1111  → 4 ones → evil
# 7  → 111   → 3 ones → odious
# 0  → 0     → 0 ones → evil

Inputs & Outputs

ItemTypeDescription
nintNonnegative integer (this page rejects negatives).
Return / printbool / textTrue if n is evil (even popcount).

Minimal workflow

Pseudocode
function is_evil(n):  // n >= 0
    ones = count_ones_in_binary(n)
    return (ones mod 2) == 0

Method comparison

MethodIdeaNotes
bit_count()Built-in popcount, then % 2Best default in modern Python
Divide by 2% 2 / // 2 to read bitsGreat for teaching binary
Kernighann &= n - 1 clears one set bitO(popcount) steps

⚡ Quick Reference

GoalPattern
Popcountn.bit_count()
Evil testn.bit_count() % 2 == 0
Binary stringbin(n) or format(n, "b")
Clear lowest set bitn &= n - 1
Classic evil0, 3, 5, 6, 9, 10, 15
Classic odious1, 2, 4, 7, 8

📋 Evil vs Odious vs Even

Related parity ideas — different levels of abstraction.

Evil
popcount even

Even count of 1-bits

Odious
popcount odd

Odd count of 1-bits

Even (decimal)
n % 2 == 0

Value parity, not bit count

Interview tip
say nonnegative

Scope the definition before coding

Context

When This Problem Shows Up

Reach for evil/odious checks when popcount parity matters.

  1. Interview bit warm-ups

    Tests binary understanding without heavy algorithms.

  2. After even-number

    Natural next step: parity of bits instead of the value.

  3. Range listing tasks

    Print all evil numbers in 1…N for small N.

  4. Teaching popcount

    Makes Hamming weight concrete with 15 vs 7.

  5. Not for negatives by default

    State nonnegative scope before coding.

Key benefit: one short boolean check that teaches popcount parity and pairs cleanly with even/odd value parity.

🔮 Live Preview

Nonnegative integers only for this definition (within JavaScript safe range).

Try 15, 7, 0, or 3.

Live result
Press "Classify" to see result.

Examples Gallery

Three complete Python programs — bit_count(), range scan with division, and Kernighan popcount. Click View Output to reveal sample console results.

📚 Getting Started

Built-in popcount with a parity check.

Example 1 — Single Check with bit_count()

Python has built-in bit_count() for integers.

python
def is_evil(n: int) -> bool:
    if n < 0:
        return False
    return n.bit_count() % 2 == 0


number = 15
if is_evil(number):
    print(f"{number} is an Evil Number.")
else:
    print(f"{number} is not an Evil Number.")

How It Works

15.bit_count() is 4, and 4 is even — so 15 is evil. Negatives return False under this page’s nonnegative policy.

⚡ Range Output

Manual bit reading by dividing by 2.

Example 2 — Evil Numbers in [1, 10]

Range output matches the classic sample.

python
def is_evil_nonneg(num: int) -> bool:
    ones = 0
    while num > 0:
        if num % 2 == 1:
            ones += 1
        num //= 2
    return ones % 2 == 0


print("Evil numbers in the range 1 to 10:")
for i in range(1, 11):
    if is_evil_nonneg(i):
        print(i, end=" ")

How It Works

The loop counts ones in binary by repeatedly taking % 2 and dividing by 2. Inclusive end uses range(1, 11).

⚙️ Kernighan Style

Clear one set bit per step for O(popcount) work.

Example 3 — Kernighan Set-Bit Loop

n &= n - 1 removes the lowest set bit each iteration.

python
def popcount_kernighan(n: int) -> int:
    ones = 0
    while n:
        n &= n - 1
        ones += 1
    return ones


def is_evil_kernighan(n: int) -> bool:
    if n < 0:
        return False
    return popcount_kernighan(n) % 2 == 0


for n in (15, 7, 0, 3):
    label = "evil" if is_evil_kernighan(n) else "odious"
    print(f"{n}: {label} (ones={popcount_kernighan(n)})")

How It Works

Each n &= n - 1 clears exactly one set bit, so the loop runs once per 1-bit. Prefer bit_count() in production; mention Kernighan as an interview follow-up.

🧠 How the Algorithm Decides

1

Count ones

Use bit_count(), a divide-by-2 loop, or Kernighan.

Popcount
2

Check count parity

Even ones → evil; odd ones → odious.

Parity
3

Reuse in a range

Apply the same helper for each value in 1…N.

Scan
=

Evil or odious

Even popcount → evil; otherwise odious.

🔎 Worked Walkthrough — n = 15

Trace popcount for the classic evil example.

StepBinary / actionOnes so far
115 = 1111
2bit_count() / four 1s4
34 % 2 == 0Evil

For contrast, 7 = 111 has 3 ones → odious.

Use Cases

Where evil/odious checks show up beyond the interview prompt.

1. Interview Warm-Ups

Popcount parity without heavy bit algorithms.

Example: write is_evil(n).

2. Teaching Binary

Connect decimal values to 1-bit counts.

Example: chalkboard 15 vs 7.

3. After Even Number

Contrast value parity with bit-count parity.

Example: 6 is even and evil.

4. Range Filters

List evil numbers in a classroom interval.

Example: 1 to 10 → 3 5 6 9 10.

5. Bit Trick Follow-Ups

Kernighan loop and hardware popcount.

Example: n &= n - 1.

6. Zero Trivia

Confirm 0 is evil before harder bit problems.

Example: ask “is zero evil?” first.

Pro Tip: say “evil = even popcount; odious = odd” before coding — it prevents mixing with decimal even/odd.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Clear Definition

    One sentence: even count of 1-bits.

  2. 2. Multiple Styles

    bit_count(), divide-by-2, and Kernighan all work.

  3. 3. Famous Test Cases

    15 vs 7 makes verification quick.

  4. 4. Rich Follow-Ups

    Odious, zero, and Kernighan are natural next questions.

Pro Tip: lead with bit_count(); offer a manual loop if asked to avoid builtins.

Usage Tips

Small habits that keep evil-number solutions interview-ready.

  1. 1. State Nonnegative Scope

    Say n ≥ 0 before coding.

  2. 2. Call Out Zero

    State that 0 is evil (zero ones).

  3. 3. Spot-Check 15 and 7

    Evil and odious classics catch parity mistakes.

  4. 4. Prefer bit_count()

    Use the builtin unless asked for a manual loop.

  5. 5. Name Odious Too

    Mention the odd-popcount complement in interviews.

Pro Tip: do not confuse “evil” with “even value” — 7 is odd but odious; 6 is even and evil.

Common Pitfalls

Mistakes that commonly break evil-number solutions.

  1. 1. Confusing with Decimal Even

    Checking n % 2 == 0 instead of popcount parity.

    → Count 1-bits, then check that count’s parity.

  2. 2. Calling Zero Odious

    Thinking zero has no classification.

    → Zero ones is even → evil.

  3. 3. Silent Negatives

    Applying popcount to negatives without a policy.

    → Reject or define two’s-complement rules explicitly.

  4. 4. Counting All Bits Including Leading Zeros

    Padding to a fixed width and counting zeros as ones.

    → Only count 1-bits in the canonical nonnegative form.

  5. 5. Exclusive Range End

    Using range(1, 10) when 10 should be included.

    → Use range(1, 11) for inclusive 1…10.

Edge Cases

Most definitions use nonnegative integers. Keep that policy clear in your code.

Zero

n = 0

Evil because ones count is 0 (even).

Negative

Policy needed

This page rejects negatives for clarity.

Representation

Binary form

Use canonical nonnegative binary representation.

Range

Include bounds

Use inclusive loops when required by the question.

Odious

Odd popcount

7, 1, 2, 4, 8 are common odious examples.

Big ints

Python OK

Arbitrary-precision ints still support bit_count().

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Hamming weight. Evil numbers are exactly those with even Hamming weight.
  • Odious. The complement class: odd number of 1-bits.
  • Zero. popcount(0) = 0 → evil.
  • Not value parity. An even decimal can be odious (e.g. 2 = 102).

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Classify classics

  • 0, 3, 15 → evil
  • 1, 7, 8 → odious

2. Match all three styles

  • bit_count vs divide vs Kernighan
  • Assert identical booleans

3. Range 1 to 20

  • List all evil numbers
  • Also list odious separately

4. Show the binary

  • Print bin(n) and popcount
  • Then the evil/odious label

Notes

  • Rule: evil means an even number of 1-bits.
  • Code: use bit_count() or manual bit loops.
  • Remember: 0 is evil; negatives need an explicit policy.
  • Single check is O(bits); Kernighan is O(popcount).

Quick Takeaway: count the 1-bits; if that count is even, the number is evil.

⏱️ Time and Space Complexity

OperationTimeExtra space
Single number popcountO(bits)O(1)
Kernighan methodO(popcount)O(1)
Range scanO(range · bits)O(1)
Wrap Up

🎉 Conclusion

An evil number has an even count of 1-bits in binary; an odd count means odious. Prefer bit_count(), keep a nonnegative policy, and remember that zero is evil.

Practice the three examples above, then continue to factorial for a classic loop-and-product warm-up.

Do not confuse popcount parity with decimal even/odd — and mention odious as the complement.

💡 Best Practices

✅ Do

  • Define nonnegative scope first
  • Prefer bit_count()
  • Test 0, 15, and 7
  • Name odious as the complement
  • Mention Kernighan as a follow-up

❌ Don’t

  • Use n % 2 as the evil test
  • Call zero odious
  • Ignore negatives without a policy
  • Count padded leading zeros as ones
  • Drop inclusive range ends

Key Takeaways

Knowledge Unlocked

Five things to remember about evil numbers

Check popcount parity the interview-friendly way.

5
Core concepts
0 02

Zero

0 is evil

Trivia
b 03

Builtin

bit_count()

Code
o 04

Complement

Odious = odd

Pair
O 05

Complexity

O(bits)

Analysis

❓ Frequently Asked Questions

A nonnegative integer is evil if its binary form has an even number of 1 bits.
If the binary 1-bit count is odd, the number is odious.
Yes. Zero has zero 1-bits, and 0 is even.
15 in binary is 1111, which has 4 ones. Four is even.
Yes, Python integers are arbitrary precision, so bit counting still works correctly.
For one number, bit counting is O(number of bits). For a range, multiply by number of values.
bit_count() is clearest in modern Python. A division or Kernighan loop shows you understand popcount.
Most definitions use nonnegative integers. This page rejects negatives for clarity.

Did you Know? 🔊

The opposite of an evil number is an odious number. Evil means an even count of 1 bits; odious means odd.

Continue to Factorial of a Number

Learn iterative and recursive ways to compute n! in Python.

Factorial tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful