检查是否是完全平方数


一个数如果其平方根是整数,这个数就称为完全平方数。换言之,当平方根是整数,这个数就称为完全平方数。

我们可以通过计算数的平方根,然后反复与 i 进行匹配来精确地获得平方根,从而检查完全平方数。当平方根超过值时,它不是完全平方数。

但是,为了减少工作量,我们不会反复检查平方根。因为我们知道,完全平方数的平方根是整数,因此我们可以将平方根加 1,检查是否为完全平方数的匹配项。

输入和输出

Input:
A number to check: 1032
Output:
1032 is not a perfect square number.

算法

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 << " 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.

更新日期: 2020 年 6 月 17 日

3K+ 浏览次数

开启你的职业生涯

通过完成本课程获得认证

开始
广告
© . All rights reserved.