打印所有整数,它们是C ++中两个给定数字的幂的和

在这个问题中,我们给了两个数字a和b以及一个整数bound,我们必须打印所有小于binding的值,即binding和a的平方和。

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<<"的幂和 "<<x<<" and "<<y<<" less than "<<bound<<" are :\n";
   powerSum(x, y, bound);
   return 0;
}

输出结果

的幂和 2 and 3 less than 25 are −
2 3 4 5 7 9 10 11 13 17 19 25