Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

ตรวจสอบว่าเป็นจำนวนกำลังสองสมบูรณ์ (Perfect Square) หรือไม่

บทนำ

จำนวนหนึ่งถูกเรียกว่า Perfect Square Number ถ้ารากที่สองของจำนวนนั้นเป็นจำนวนเต็ม กล่าวอีกนัยหนึ่ง เมื่อรากที่สองเป็นจำนวนเต็ม จำนวนนั้นเรียกว่า Perfect Square Number

เราสามารถตรวจสอบ Perfect Square ได้โดยการหารากที่สองของจำนวนนั้น และเปรียบเทียบกับ i ซ้ำๆ เพื่อหารากที่สองที่แน่นอน เมื่อรากที่สองเกินค่าแล้ว แสดงว่าไม่ใช่ Perfect Square Number

แต่วิธีนี้เพื่อลดความพยายาม เราไม่ได้ตรวจสอบรากที่สองซ้ำๆ เนื่องจากเรารู้ว่ารากที่สองของ Perfect Square Number เป็นจำนวนเต็ม เราจึงเพิ่มรากที่สองทีละหนึ่ง และตรวจสอบการ match

อินพุตและเอาต์พุต

Input: ตัวเลขที่ต้องการตรวจสอบ: 1032
Output: 1032 ไม่ใช่ Perfect Square Number

อัลกอริทึม

isPerfectSquare(num)
Input: ตัวเลข
Output: True ถ้าเป็น Perfect Square Number และพิมพ์รากที่สองด้วย

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

ตัวอย่างโค้ด (C++)

#include <iostream>
using namespace std;

int isPerfectSquare(int num) {
    if (num < 0)
        return -1;  // ตัวเลขลบไม่ใช่ square term ที่ถูกต้อง
    int sqRoot = 1, sq;
    while ((sq = (sqRoot*sqRoot)) <= num) {
        // เมื่อกำลังสองของรากที่สองยังไม่เกินตัวเลข
        if (sq == num)
            return sqRoot;
        sqRoot++;  // เนื่องจากรากที่สองของ perfect square เป็นจำนวนเต็มเสมอ
    }
    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.