Given two integers N and B, the task is to find the count of natural numbers of Base B up to N digits.
Input: N = 2, B = 10
1, 2, 3, 4, 5, 6, 7, 8, 9 are 1 digit Natural numbers of Base 10.
10, 11, 12………99 are 2 digit Natural numbers of Base 10
So, total = 9 + 90 = 99
Input: N = 2, B = 16
There are a total of 240 two digit hexadecimal numbers and 15 one digit hexadecimal numbers.
Therefore, 240 + 15 = 255.
Approach: On observing carefully the count of numbers with N digits in base B is a geometric progression formed with the first term being (B – 1) and a common ratio of B.
Nth term = Number of natutal numbers of N digits in Base B = (B – 1) * BN – 1
Finally, count of all natural numbers in Base B up to N digits can be found out by iterating a loop from 1 to N and calculating the sum of ith term using the above formula.
Below is the implementation of the above approach:
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.