檢查是否是完全平方數
一個數如果其平方根是整數,這個數就稱為完全平方數。換言之,當平方根是整數,這個數就稱為完全平方數。
我們可以透過計算數的平方根,然後反覆與 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.
廣告