สมมุติว่าให้ตัวเลขมา เราต้องตรวจสอบว่าตัวเลขนั้นเป็นกำลังสองสมบูรณ์หรือไม่ เราจะไม่ใช้การดำเนินการสแควร์รูทเพื่อตรวจสอบ สมมติว่ามีตัวเลข 1024 นี่คือกำลังสองสมบูรณ์ แต่ 1,000 ไม่ใช่กำลังสองสมบูรณ์ ตรรกะง่าย ๆ เราต้องทำตามอัลกอริธึมนี้เพื่อให้ได้ผลลัพธ์
อัลกอริทึม
isPerfectSquare(n) −
อินพุต − หมายเลข n
ผลผลิต − จริง ถ้าตัวเลขเป็นกำลังสองสมบูรณ์ มิฉะนั้น เท็จ
begin for i := 1, i2 ≤ n, increase i by 1: if n is divisible by i, and n / i = i, then return true done return false end
ตัวอย่าง
#include <iostream>
using namespace std;
bool isPerfectSquare(int number) {
for (int i = 1; i * i <= number; i++) {
if ((number % i == 0) && (number / i == i)) {
return true;
}
}
return false;
}
int main() {
int n = 1024;
if(isPerfectSquare(n)){
cout << n << " is perfect square number";
} else {
cout << n << " is not a perfect square number";
}
} ผลลัพธ์
1024 is perfect square number