是否检查完美正方形
如果数字的平方根是整数,则该数字被称为完美平方数。换句话说,当平方根是整数时,该数字称为理想平方数。
我们可以通过找到该数字的平方根来检查完美平方,然后一次又一次与i匹配以获得确切的平方根。当平方根与值相交时,它不是理想的平方数。
但是这里为了减少工作量,我们没有一次又一次地检查平方根。众所周知,理想平方数的平方根是整数,那么我们可以将平方根加1,然后检查理想平方匹配。
输入输出
Input: A number to check: 1032 Output: 1032 不是一个完美的平方数。
算法
isPerfectSquare(num)
输入: 数字。
输出:如果一个数字是理想的平方数,则为True,并打印平方根。
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 << " 不是一个完美的平方数。";
}输出结果
Enter a number to check whether it is perfect square or not: 1032 1032 不是一个完美的平方数。