VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-numbers-from-1-to-n-that-have-4-as-a-a-digit/

⇱ Count numbers from 1 to n that have 4 as a digit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count numbers from 1 to n that have 4 as a digit

Last Updated : 21 Mar, 2025

Given an integer n. The task is to count all numbers from 1 to n that contain the digit 4 at least once in their representation.

Examples: 

Input: n = 20
Output: 2
Explanation: The numbers 4 and 14 contain the digit 4 at least once.

Input: n = 50
Output: 14
Explanation: The numbers 4, 14, 24, 34, and 40-49 contain the digit 4 at least once.

Input: n = 3
Output: 0
Explanation: None of the numbers 1, 2, or 3 contain the digit 4.

[Brute Force Approach] Check Every Number From 1 to n - O(nlog(n)) Time and O(1) Space

The idea is to iterate through all numbers from 1 to n and check if they contain the digit 4. For each number, we extract digits one by one using num % 10 and compare them to 4. If a match is found, we increase the count.


Output
14

[Expected Approach] Using Mathematics - O(log n) Time and O(logn) Space

The idea is to find a mathematical pattern to count numbers containing the digit 4 efficiently instead of checking each number. We observe that for numbers up to 10^d, the count follows a recurrence relation: count(10^d) = 9 * count(10^(d-1)) + 10^d - 1. Using this, we precompute results dynamically to handle overlapping subproblems, significantly reducing redundant calculations.

To compute the count for n, we first determine its most significant digit (msd) and handle three cases:

  • If MSD == 4, we sum counts up to MSD * 10^(d-1) and recursively process the remainder.
  • If MSD > 4, we adjust for skipped ranges and add 10^d-1
  • if MSD < 4, we only sum up to MSD * count(10^(d-1)) before recursion.

How does the above approach work?

Count of numbers (having 4) from 0 to 9 = 1
Count of numbers from 0 to 99 = 4 Comes in Every 10th Number + There are ten 4s in numbers from 40 to 49 = 1*9 + 10
Count of numbers from 0 to 999 = 19*9 + 100 = 271

In general, we can write
count(10d) = 9 * count(10d - 1) + 10d - 1

If MSD is 4. For example if n = 428, then count of numbers is sum of following.
1) Count of numbers from 1 to 399
2) Count of numbers from 400 to 428 which is 29.

IF MSD > 4. For example if n is 728, then count of numbers is sum of following.
1) Count of numbers from 1 to 399 and count of numbers from 500 to 699, i.e., "a[2] * 6"
2) Count of numbers from 400 to 499, i.e. 100
3) Count of numbers from 700 to 728, recur for 28

IF MSD < 4. For example if n is 328, then count of numbers is sum of following.
1) Count of numbers from 1 to 299 a
2) Count of numbers from 300 to 328, recur for 28


Output
14
Comment