使用 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

更新於: 2020年6月6日

313 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.