📜  N位的所有可能数字和基数B(不带前导零)

📅  最后修改于: 2021-04-21 22:18:25             🧑  作者: Mango

给定数字“ N”和基数“ B”,任务是计算所有“ N”个数字,且基数“ B”中不带前导零。

例子:

Input: N = 2, B = 2
Output: 2
All possible numbers without 
leading zeros are 10 and 11.

Input: N = 5, B = 8
Output: 28672

方法:

  • 如果基数为“ B”,则数字的每个数字都可以取[0,B-1]范围内的任何值。
  • 所以,B ^{N}底数为“ B”的数字可以为“ N”(包括带前导零的数字)。
  • 并且,如果我们将第一个数字固定为“ 0”,那么其余的“ N-1”个数字就可以构成总共B ^{(N-1)}数字。
  • 因此,可能带有基数“ B”且不含前导零的“ N”个数字的总数为B ^{N} – B ^{(N-1)}

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
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


输出:
3072