使用 C++ 统计所有排列都大于该数的自然数
给定一个自然数,例如 num,任务是计算所有这些自然数的个数,其所有排列都大于该数。
我们遵循以下条件 −
数据只能是自然数
自然数的所有可能排列或组合必须等于或大于给定数。例如,数字是 20
考虑从 1 到 20 的所有数字,即 1、2、3、4、5、6、7、8、9、10、11、12、13、14、15、16、17、18、19、20
现在检查那些排列或组合等于或大于给定数字(即 20)的数字。数字为 1、2、3、4、5、6、7、8、9、11=11、12<21、13<31、14<41、15<51、16<61、17<71、18<81、19<91。所以计数将是 18。
输入 − num = 10
输出 − 计数为 9
说明 − 数字 1、2、3、4、5、6、7、8、9 在任何排列方式下都等于该数字。
输入 − num = 13
输出 − 计数为 12
说明 − 数字 1、2、3、4、5、6、7、8、9、11、12<21、13<31 在任何排列方式下都等于或大于该数字。
下面程序中使用的方案如下
输入数字 num 的值
将 max_size 设置为 9,因为始终至少有 9 个数字的排列等于或大于该数字本身。
从 0 开始循环到 max_size
在循环内,创建一个列表类型的变量,并检查 i 是否小于或等于 num。如果是,则将 i 插入列表并使计数加 1
从列表的末尾遍历到开头,并从第一个元素开始另一个循环到 9。
检查 temp 是否小于或等于 num,如果是,则将 temp 推送到列表的前面并使计数加 1
返回计数
打印结果。
示例
#include<bits/stdc++.h>
using namespace std;
//function to Count natural numbers whose
//all permutation are greater than that number
void count(int num){
int count = 0;
int max_size = 9;
for (int i = 1; i <= max_size; i++){
list<int> lists;
if (i <= num){
//insert element at the end of the list
lists.push_back(i);
count = count + 1;
}
//iterator starts from the last of the list
for(auto iter = lists.end(); iter != lists.begin(); ++iter){
int first_ele = lists.front();
lists.pop_front();
for (int next = first_ele%10; next <= 9; next++){
int temp = first_ele*10 + next;
if (temp <= num){
lists.push_front(temp);
count++;
}
}
}
}
cout<<"count of num "<<num <<" is "<<count<<endl;
}
int main(){
count(1);
count(9);
count(7);
count(0);
count(12);
return 0;
}输出
如果我们运行以上代码,我们将得到以下输出:
count of num 1 is 1 count of num 9 is 9 count of num 7 is 7 count of num 0 is 0 count of num 12 is 11
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP