C++ 中的強大整數
假設我們有三個整數 'a'、'b' 和 'limit'。任務是在 [a, limit] 範圍內列印數字。這些數字的列表被稱為強大整數,表示為:
a^i + b^j 其中 i >= 0 且 j >= 0
例如
輸入-1
a = 2
b = 5
limit = 10
輸出
[2, 3, 4, 5, 6, 7, 9]
說明:對於每個 i 和 j,
2^0 + 5^0 = 2 , 2^0 + 5^1= 6
2^1 + 5^0 = 3 , 2^1 + 5^1= 7
2^2 + 5^0 =5 , 2^3 + 5^0= 9
解決此問題的方法
解決此特定問題的蠻力方法是,我們將使用兩個巢狀迴圈並迭代到限制。然後,我們將找到上界中每個指數的兩個數字的總和,並將結果數字插入列表中。
- 取三個數字 'a'、'b' 和 'limit'。
- 函式 powerfulnumbers(int a, int b, int limit) 將數字 'a'、'b' 和 'limit' 作為輸入。該函式返回所有強大數字的列表,使得 a^i + b^j 其中 i >= 0 且 j >= 0。
- 取兩個巢狀迴圈,範圍到限制,並且每次透過與其索引相乘來查詢強大數字。
- 如果數字位於 [a, limit] 範圍內,則將該數字儲存在集合中(以避免數字重複)。
- 迭代集合並列印輸出。
示例
#include <bits/stdc++.h> using namespace std; void powerfulNum(int a, int b, int limit) { set < int > s; for (int i = 1; i < limit; i *= a) { for (int j = 1; j < limit; j *= b) { if (i + j <= limit) { s.insert(i + j); } else break; if (b == 1) break; } if (a == 1) break; } for (auto it: s) { cout << it << " "; } } int main() { int a = 2; int b = 5; int limit = 10; powerfulNum(a, b, limit); return 0; }
執行以上程式碼將生成以下輸出:
輸出
2 3 5 6 7 9
這裡,範圍為 2 到 10 的所有強大數字為 [2, 3, 4, 6, 7, 9]。
廣告