Cho số n. Tìm số bình phương hoàn hảo nhỏ nhất lớn hơn n. Ví dụ n=1000 thì kết quả 1024 = 32².
Giải pháp: tính căn bậc hai của n, lấy phần nguyên (floor), sau đó bình phương của (floor + 1).
Ví dụ mã nguồn
#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);
}
Kết quả đầu ra
Nearest perfect square: 1024