ในปัญหานี้ เราได้รับตัวเลขสองตัว a และ b และผูกจำนวนเต็ม และเราต้องพิมพ์ค่าทั้งหมดที่น้อยกว่าการผูก ซึ่งเป็นผลรวมของกำลังสองของ a และ b .
Bound >= ai + bj
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน −
Input: a=2, b=3, bound=8 Output: 2 3 4 5 7
ในการแก้ปัญหานี้ เราจะใช้การวนซ้ำซ้อนโดยใช้สองตัวแปร i และ j จาก 0 วงรอบนอกจะมีเงื่อนไขสิ้นสุด xi =ถูกผูกไว้ และวงในจะมีเงื่อนไขสิ้นสุด xi + yj> ถูกผูกไว้ . สำหรับการวนซ้ำของวงในแต่ละครั้ง เราจะเก็บค่าของ 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