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

CServer Side ProgrammingProgramming

Here we will see one problem, We have N and base B. Our task is to count all N digit numbers of base B without any leading 0s. So if N is 2 and B is 2 there will be four numbers 00, 01, 10, 11. So only two of them are valid for this section. These are 10, 11, there are no leading 0s.

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 0s). The first digit is 0m if we ignore it there are BN-1 number. So total N digit numbers which has no leading 0 are BN – BN-1

Algorithm

countNDigitNum(N, B)

Begin
   total := BN
   with_zero := BN-1
   return BN – BN-1
End

Example

#include <iostream>
#include <cmath>
using namespace std;
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;
   cout << "Number of values: " << countNDigitNum(N, B);
}

Output

Number of values: 28672
raja
Published on 31-Jul-2019 13:11:26
Advertisements