All possible numbers of N digits and base B without leading zeros (original) (raw)

Last Updated : 16 Aug, 2022

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:

Below is the implementation of the above approach:

C++ `

// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;

// function to count // all permutations void countPermutations(int N, int B) { // count of // all permutations int x = pow(B, N);

// count of permutations
// with leading zeros
int y = pow(B, N - 1);

// Return the permutations
// without leading zeros
cout << x - y << "\n";

}

// Driver code int main() {

int N = 6;
int B = 4;

countPermutations(N, B);

return 0;

}

Java

// Java implementation of the approach

class GFG { // function to count // all permutations static void countPermutations(int N, int B) { // count of // all permutations int x = (int)Math.pow(B, N);

// count of permutations
// with leading zeros
int y = (int)Math.pow(B, N - 1);

// Return the permutations
// without leading zeros
System.out.println(x - y);

}

// Driver code public static void main(String[] args) { int N = 6; int B = 4;

countPermutations(N, B);

} }

// This code is contributed by mits

Python3

Python3 implementation of the approach

function to count all permutations

def countPermutations(N, B):

# count of all permutations 
x = B ** N 

# count of permutations 
# with leading zeros 
y = B ** (N - 1) 

# Return the permutations 
# without leading zeros 
print(x - y) 

Driver code

if name == "main":

N, B = 6, 4
countPermutations(N, B) 

This code is contributed by Rituraj Jain

C#

// C# implementation of the approach

using System; class GFG { // function to count // all permutations static void countPermutations(int N, int B) { // count of // all permutations int x = (int)Math.Pow(B, N);

// count of permutations
// with leading zeros
int y = (int)Math.Pow(B, N - 1);

// Return the permutations
// without leading zeros
Console.WriteLine(x - y);

}

// Driver code public static void Main() { int N = 6; int B = 4;

countPermutations(N, B);

} }

// This code is contributed // by Akanksha Rai(Abby_akku)

` PHP ``

x=pow(x = pow(x=pow(B, $N); // count of permutations // with leading zeros y=pow(y = pow(y=pow(B, $N - 1); // Return the permutations // without leading zeros echo ($x - $y), "\n"; } // Driver code $N = 6; $B = 4; countPermutations($N, $B); // This code is contributed // by Sach_Code` ?>

`` JavaScript `

`

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.