숫자의 제곱근이 정수인 경우 해당 숫자를 완전제곱수라고 합니다. 즉, 제곱근이 정수일 때 그 수를 완전제곱수라고 합니다.
그 수의 제곱근을 찾아서 완전제곱수를 확인하고 i와 계속해서 일치시켜 정확한 제곱근을 얻을 수 있습니다. 제곱근이 값과 교차하면 완전제곱수가 아닙니다.
하지만 여기서는 노력을 줄이기 위해 제곱근을 반복해서 확인하지 않았습니다. 완전제곱수의 제곱근이 정수라는 것을 알고 있으므로 제곱근을 1씩 증가시켜 완전제곱수가 맞는지 확인할 수 있습니다.
입력 및 출력
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.