在 C++ 中列印所有兩個給定數的冪之和的整數
在這個問題中,我們給出了兩個數 a 和 b 以及一個整數 bound,我們必須打印出所有小於 bound 的值,該值是 **a 和 b** 的平方和。
Bound >= ai + bj
我們舉一個例子來理解這個問題 -
Input: a=2, b=3, bound=8 Output: 2 3 4 5 7
為了解決這個問題,我們將使用巢狀迴圈,其中使用兩個變數 i 和 j 從 0 開始。外層迴圈的結束條件是 **xi = bound**,內層迴圈的結束條件是 **xi + yj > bound**。對於內層迴圈的每次迭代,我們將 xi + yi 的值儲存在一個包含所有此類值的排序列表中。然後在最後列印列表中的所有值。
例
展示我們的解決方案實現的程式 -
#include <bits/stdc++.h>
using namespace std;
void powerSum(int x, int y, int bound) {
set<int> sumOfPowers;
vector<int> powY;
int i;
powY.push_back(1);
for (i = y; i < bound; i = i * y)
powY.push_back(i);
i = 0;
while (true) {
int powX = pow(x, i);
if (powX >= bound)
break;
for (auto j = powY.begin(); j != powY.end(); ++j) {
int num = powX + *j;
if (num <= bound)
sumOfPowers.insert(num);
else
break;
}
i++;
}
set<int>::iterator itr;
for (itr = sumOfPowers.begin(); itr != sumOfPowers.end(); itr++) {
cout<<*itr <<" ";
}
}
int main() {
int x = 2, y = 3, bound = 25;
cout<<"Sum of powers of "<<x<<" and "<<y<<" less than "<<bound<<" are :\n";
powerSum(x, y, bound);
return 0;
}輸出
Sum of powers of 2 and 3 less than 25 are − 2 3 4 5 7 9 10 11 13 17 19 25
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP