สมมติเรามีตัวเลข n งานของเราคือหากำลังสองสมบูรณ์ถัดไปของ n ถ้าตัวเลข n = 1000 กำลังสองสมบูรณ์ถัดไปคือ 1024 = 322
เพื่อแก้ปัญหานี้ เราหารากที่สองของตัวเลข n ที่กำหนด แล้วเอาค่า floor หลังจากนั้นแสดงกำลังสองของ (ค่า floor + 1)
ตัวอย่าง
#include <iostream>
#include <cmath>
using namespace std;
int justGreaterPerfectSq(int n) {
int sq_root = sqrt(n);
return (sq_root + 1)*(sq_root + 1);
}
int main() {
int n = 1000;
cout << "Nearest perfect square: " << justGreaterPerfectSq(n);
}
ผลลัพธ์
Nearest perfect square: 1024