检查是否是完全平方数


如果某个数的平方根是整数,那么该数被称为完全平方数。换言之,当平方根是整数时,该数被称为完全平方数。

我们通过求出该数的平方根并一次又一次地与 i 进行匹配以得到确切的平方根来检查完全平方数。当平方根越过该值时,它就不是一个完全平方数。

但是在这里,为了减少工作量,我们没有一遍又一遍地检查平方根。因为我们知道完全平方数的平方根是整数,那么我们可以将平方根加一,并检查完全平方数的匹配情况。

输入和输出

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 日

3000+ 次浏览

开启你的职业生涯

通过完成课程获取认证

开始
广告
© . All rights reserved.