檢查是否是完全平方數


如果某個數的平方根是整數,那麼該數被稱為完全平方數。換言之,當平方根是整數時,該數被稱為完全平方數。

我們透過求出該數的平方根並一次又一次地與 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+ 次瀏覽

開啟你的職業生涯

透過完成課程獲取認證

開始
廣告