CPE 一顆星選集 49 道必考題
題目連結:https://zerojudge.tw/ShowProblem?problemid=e566
內容
給定兩非負整數 n, m (n, m < 2000000000),不斷拿 n 除以 m ,並更新 n = n / m,若直到 n = 1 的過程中皆可整除,依序輸出每個 n ,若否,輸出 ‘Boring!’。
範例輸入
125 5
30 3
80 2
81 3
範例輸出
125 25 5 1
Boring!
Boring!
81 27 9 3 1
想法
不斷將 n 除以 m 並更新 n ,使用 queue 紀錄每個 n ,若皆可整除,則運用 queue 特性(先進先出)印出,若否,則輸出’Boring!’,每完成一筆測資後,需將 queue 清空(將裡面元素不斷 pop 出來,直到 empty)。
程式碼
    
    
        1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
   | #include <bits/stdc++.h> #define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr) using namespace std;
  int main(){     fastio;     int n, m, temp;     queue<int> q;     while(cin >> n >> m){         if(m == 0){             cout << "Boring!\n";             continue;         }         q.push(n);         while(n != 1){             if(n % m == 0){                 n /= m;                 q.push(n);             }             else{                 cout << "Boring!";                 while(!q.empty()) q.pop();                 break;             }         }         while(!q.empty()){             temp = q.front();             q.pop();             cout << temp << " ";         }         cout << "\n";     } }
   |