Count 'honestly even' numbers from 1 to n
A natural number is "honestly even" if every digit in its decimal form is even (4826 and 8802 qualify; 79, 301, and 1478 do not). Return how many honestly-even numbers there are from 1 to n inclusive.
Examples: n=1 → 0; n=2 → 1; n=10 → 4 (the numbers 2, 4, 6, 8).
def count_honestly_even(n: int) -> int:
# your code here
Write the implementation.
Count numbers whose every digit is in {0,2,4,6,8}. A direct scan: sum(1 for k in range(1, n+1) if all(d in '02468' for d in str(k))). The trap is reading 'even number' as value % 2 == 0 — here the test is per-digit, not parity of the whole number.
- ✗Counting plain even numbers (value % 2) instead of all-digits-even
- ✗Checking only the last digit
- ✗Using digit-sum parity instead of per-digit evenness
- →Why does 10 fail the honestly-even test?
- →How would a digit-DP approach scale this for huge n?
The condition is per-digit, not whole-number parity: every decimal digit must be in {0,2,4,6,8}.
def count_honestly_even(n: int) -> int:
return sum(1 for k in range(1, n + 1)
if all(d in '02468' for d in str(k)))
For n=10 only 2, 4, 6, 8 pass — 10 has the odd digit 1 — so the count is 4. n=1 gives 0 (1 is odd) and n=2 gives 1. The leading digit can never be 0, so no spurious numbers are counted. The brute scan is O(n · digits); for very large n a digit-DP counts without enumerating every value.