Home > Backend Development > C++ > body text

All possible N digits and base B, but excluding numbers with leading zeros

王林
Release: 2023-08-29 21:57:06
forward
621 people have browsed it

All possible N digits and base B, but excluding numbers with leading zeros

Here we will see a problem where we have N and base B. Our task is to count the number of N digits in base B without leading 0's. So if N is 2 and B is 2, then there will be four numbers 00, 01, 10, and 11. So only two of the numbers are valid for this part. They are 10, 11, without leading 0's.

If the base is B, then there are 0 to B-1 different numbers. So B^N different N-digit numbers (including leading 0s) can be generated. If we ignore the first number 0, then there are B^(N-1) numbers. So the total number of N digits without leading 0 is B^N - B^(N-1)

Algorithm

countNDigitNum(N, B)

Begin
   total := B<sup>N</sup>
   with_zero := B<sup>N-1</sup>
   return BN &ndash; B<sup>N-1</sup>
End
Copy after login

Example## The Chinese translation of # is:

Example

#include <iostream>
#include <cmath>
using namespace std;
int countNDigitNum(int N, int B) {
   int total = pow(B, N);
   int with_zero = pow(B, N - 1);
   return total - with_zero;
}
int main() {
   int N = 5;
   int B = 8;
   cout << "Number of values: " << countNDigitNum(N, B);
}
Copy after login

Output

Number of values: 28672
Copy after login

The above is the detailed content of All possible N digits and base B, but excluding numbers with leading zeros. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template