All possible numbers of N digits and base B without leading zeros
Given a number of digits ‘N’ and base ‘B’, the task is to count all the ‘N’ digit numbers without leading zeros that are in base ‘B’
Examples:
Input: N = 2, B = 2
Output: 2
All possible numbers without
leading zeros are 10 and 11.
Input: N = 5, B = 8
Output: 28672
Approach:
- If the base is ‘B’ then every digit of the number can take any value within the range [0, B-1].
- So, B‘N’ digit numbers are possible with base ‘B’ (including the numbers with leading zeros).
- And, if we fix the first digit as ‘0’ then the rest of the ‘N-1’ digits can form a total of Bnumbers.
- So, the total number of ‘N’ digit numbers with base ‘B’ possible without leading zeros are B– B.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countPermutations( int N, int B)
{
int x = pow (B, N);
int y = pow (B, N - 1);
cout << x - y << "\n" ;
}
int main()
{
int N = 6;
int B = 4;
countPermutations(N, B);
return 0;
}
|
Java
class GFG
{
static void countPermutations( int N, int B)
{
int x = ( int )Math.pow(B, N);
int y = ( int )Math.pow(B, N - 1 );
System.out.println(x - y);
}
public static void main(String[] args)
{
int N = 6 ;
int B = 4 ;
countPermutations(N, B);
}
}
|
Python3
def countPermutations(N, B):
x = B * * N
y = B * * (N - 1 )
print (x - y)
if __name__ = = "__main__" :
N, B = 6 , 4
countPermutations(N, B)
|
C#
using System;
class GFG
{
static void countPermutations( int N, int B)
{
int x = ( int )Math.Pow(B, N);
int y = ( int )Math.Pow(B, N - 1);
Console.WriteLine(x - y);
}
public static void Main()
{
int N = 6;
int B = 4;
countPermutations(N, B);
}
}
|
PHP
<?php
function countPermutations( $N , $B )
{
$x = pow( $B , $N );
$y = pow( $B , $N - 1);
echo ( $x - $y ), "\n" ;
}
$N = 6;
$B = 4;
countPermutations( $N , $B );
?>
|
Javascript
<script>
function countPermutations(N, B)
{
var x = Math.pow(B, N);
var y = Math.pow(B, N - 1);
document.write( x - y );
}
var N = 6;
var B = 4;
countPermutations(N, B);
</script>
|
Time Complexity: O(logn), since pow function takes logn time to find the power of a number to base n.
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
16 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...