在 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