All possible numbers of N digits and base B without leading zeros?

Here we will see one problem where we have N and base B. Our task is to count all N digit numbers of base B without any leading zeros. So if N is 2 and B is 2, there will be four numbers: 00, 01, 10, 11. Only two of them are valid for this problem − 10 and 11, as they have no leading zeros.

If the base is B, then there are 0 to B − 1 different digits. So BN number of different N digit values can be generated (including leading zeros). Numbers with leading zero start with 0, so if we ignore the first digit, there are BN-1 such numbers. Therefore, total N digit numbers without leading zeros are BN − BN-1.

Syntax

int countNDigitNum(int N, int B);
// Returns count of N-digit numbers in base B without leading zeros

Algorithm

countNDigitNum(N, B)
Begin
   total := B^N
   with_zero := B^(N-1)
   return total - with_zero
End

Example

Let's implement the algorithm to count N-digit numbers in base B without leading zeros −

#include <stdio.h>
#include <math.h>

int countNDigitNum(int N, int B) {
    int total = pow(B, N);
    int with_zero = pow(B, N - 1);
    return total - with_zero;
}

int main() {
    int N = 5;
    int B = 8;
    
    printf("For N = %d digits in base %d:<br>", N, B);
    printf("Total possible numbers: %.0f<br>", pow(B, N));
    printf("Numbers with leading zeros: %.0f<br>", pow(B, N - 1));
    printf("Numbers without leading zeros: %d<br>", countNDigitNum(N, B));
    
    // Test with different values
    printf("\nOther examples:<br>");
    printf("N=2, B=2: %d numbers<br>", countNDigitNum(2, 2));
    printf("N=3, B=10: %d numbers<br>", countNDigitNum(3, 10));
    
    return 0;
}
For N = 5 digits in base 8:
Total possible numbers: 32768
Numbers with leading zeros: 4096
Numbers without leading zeros: 28672

Other examples:
N=2, B=2: 2 numbers
N=3, B=10: 900 numbers

How It Works

  • Total numbers: BN represents all possible N-digit combinations in base B
  • Leading zero numbers: BN-1 represents numbers that start with 0
  • Valid numbers: BN − BN-1 = BN-1(B − 1)

Conclusion

The formula BN − BN-1 efficiently counts N-digit numbers in any base B without leading zeros. This approach works by subtracting invalid numbers (with leading zeros) from the total possible combinations.

Updated on: 2026-03-15T11:12:12+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements