不包含数字 9 的 n 位数的个数
假设你有一个给定的数字 N。现在,你想找到那些不包含数字 9 的 N 位数。这个问题可以用排列组合的数学方法来解决。在这篇文章中,我们将使用 C++ 找到这些数字并计算它们的个数。
假设你必须找到不包含数字 9 的一位数。那么,这些数字是 (0 – 8)。总共有 8 个这样的数字。同样,我们必须找到 N 位数的个数。
在这里,我们将得到 N 的值,然后我们必须找到所有不包含数字 9 的 N 位数的个数。
输入输出场景
给定 N。不包含数字 9 的 N 位数的个数是输出。
Input: N = 2 Output: 72 Input: N = 3 Output: 648
对于N = 2,不包含数字 9 的可能数字是所有数字,除了90 – 99和那些个位数为 9 的数字。这样的数字共有 72 个。
假设有 Z 个 N 位数。使用排列组合,形成的 N 位数的总数等于9 * 10N – 1。这是因为每个数字都由(0 – 9)之间的数字构成,除了首位数字不能为 0。
现在,在我们的问题中,我们必须找到那些不包含数字9的数字。这意味着需要排除一个数字,即 9。所以公式变为8 * 9N – 1。
使用 pow() 函数
pow() 函数接受两个参数作为输入,将第一个参数提升到第二个参数的幂,并返回结果。我们将使用pow()函数来计算9N – 1
#include <iostream>
#include <cmath>
using namespace std;
int possibleNumbers(int N){
return 8 * pow(9, N - 1);
}
int main() {
int N = 3;
cout << "Number of " << N << " digit number which do not contain 9 are " <<
possibleNumbers(N);
return 0;
}
输出
Number of 3 digit number which do not contain 9 are 648
使用迭代和 if 语句
使用pow()函数会涉及各种计算,这可能会降低程序的效率。与其这样,我们可以尝试一种更高效的方法,该方法涉及使用 for 循环和 if 语句进行指数运算。
示例
#include <iostream>
#include <cmath>
using namespace std;
long long power(int base, int exp) {
int a = 1;
for (int j = 1; j <= exp; ++j) {
a *= base;
}
return a;
}
int possibleNumbers(int N) {
int x = power(9, N - 1);
return 8 * x;
}
int main() {
int N = 2;
cout << "Number of " << N << " digit number which do not contain 9 are " <<
possibleNumbers(N);
return 0;
}
输出
Number of 2 digit number which do not contain 9 are 72
结论
我们讨论了查找不包含数字 9 的 N 位数的不同方法。第一种方法是使用<cmath>库的pow()函数。第二种方法是使用for循环和if语句来计算指数运算。后者效率更高,因为它降低了时间复杂度。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP