Find the total count of numbers up to N digits in a given base B
Given two integers N and B, the task is to find the count of natural numbers of Base B up to N digits.
Examples:
Input: N = 2, B = 10
Output: 99
Explanation:
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
Output: 255
Explanation:
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.
Therefore,
Nth term = Number of natural 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:
C++
#include <bits/stdc++.h>
using namespace std;
int count( int N, int B)
{
int sum = 0;
for ( int i = 1; i <= N; i++) {
sum += (B - 1) * pow (B, i - 1);
}
return sum;
}
int main()
{
int N = 2, B = 10;
cout << count(N, B);
return 0;
}
|
Java
class GFG{
static int count( int N, int B)
{
int sum = 0 ;
for ( int i = 1 ; i <= N; i++){
sum += (B - 1 ) * Math.pow(B, i - 1 );
}
return sum;
}
public static void main(String[] args)
{
int N = 2 , B = 10 ;
System.out.print(count(N, B));
}
}
|
Python3
from math import pow
def count(N, B):
sum = 0
for i in range ( 1 , N + 1 ):
sum + = (B - 1 ) * pow (B, i - 1 )
return sum
if __name__ = = '__main__' :
N = 2
B = 10
print ( int (count(N, B)))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int count( int N, int B)
{
int sum = 0;
for ( int i = 1; i <= N; i++)
{
sum += ( int )((B - 1) * Math.Pow(B, i - 1));
}
return sum;
}
public static void Main(String[] args)
{
int N = 2, B = 10;
Console.Write(count(N, B));
}
}
|
Javascript
<script>
function count(N, B)
{
var sum = 0;
for ( var i = 1; i <= N; i++)
{
sum += (B - 1) * Math.pow(B, i - 1);
}
return sum;
}
var N = 2, B = 10;
document.write(count(N, B));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
16 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...