มีการกล่าวถึงตัวเลขว่าเป็นจำนวนเต็มกำลังสองถ้ารากที่สองของตัวเลขนั้นเป็นจำนวนเต็ม กล่าวอีกนัยหนึ่ง เมื่อรากที่สองเป็นจำนวนเต็ม จะเรียกว่าจำนวนเต็มกำลังสอง
เราตรวจสอบกำลังสองสมบูรณ์ได้โดยการหารากที่สองของจำนวนนั้นแล้วจับคู่กับ i ซ้ำแล้วซ้ำเล่าเพื่อให้ได้รากที่สองที่แน่นอน เมื่อรากที่สองตัดกับค่า จะไม่ใช่จำนวนเต็มกำลังสองสมบูรณ์
แต่ที่นี่เพื่อลดความพยายาม เรายังไม่ได้ตรวจสอบสแควร์รูทซ้ำแล้วซ้ำอีก ดังที่เราทราบดีว่าสแควร์รูทของจำนวนเต็มกำลังสองเป็นจำนวนเต็ม จากนั้นเราก็สามารถเพิ่มสแควร์รูททีละหนึ่ง และตรวจสอบหาการจับคู่กำลังสองที่สมบูรณ์แบบ
อินพุตและเอาต์พุต
Input: A number to check: 1032 Output: 1032 is not a perfect square number.
อัลกอริทึม
isPerfectSquare(num)
ป้อนข้อมูล: เลขที่
ผลลัพธ์: เป็นจริงถ้าตัวเลขเป็นจำนวนเต็มกำลังสอง และพิมพ์รากที่สองด้วย
Begin if num < 0, then exit sqRoot := 1 sq := sqRoot^2 while sq <= num, do if sq = num, then return sqRoot sqRoot := sqRoot + 1 sq := sqRoot^2 done otherwise return error End
ตัวอย่าง
#include<iostream>
using namespace std;
int isPerfectSquare(int num) {
if(num < 0)
return -1; //a -ve number is not a valid square term
int sqRoot = 1, sq;
while((sq =(sqRoot*sqRoot)) <= num) { //when square of square root is not crossed the number
if(sq == num)
return sqRoot;
sqRoot++; //as square root of a perfect square is always integer
}
return -1;
}
int main() {
int num, res;
cout << "Enter a number to check whether it is perfect square or not: ";
cin >> num;
if((res = isPerfectSquare(num)) != -1)
cout << num << " is a perfect square number, square root: " << res;
else
cout << num << " is not a perfect square number.";
} ผลลัพธ์
Enter a number to check whether it is perfect square or not: 1032 1032 is not a perfect square number.