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

ผลรวมของจำนวนกำลังสองใน C++

ปัญหา

สมมติว่าเรามีจำนวนเต็มที่ไม่เป็นลบ c เราต้องตัดสินใจว่ามีจำนวนเต็ม a และ b สองตัวหรือไม่ ที่ทำให้ a^2 + b^2 = c

เช่น ถ้าผนวกเข้าเป็น 61 ผลลัพธ์จะเป็น True เนื่องจาก 61 = 5^2 + 6^2

วิธีแก้ปัญหา

  1. กำหนดฟังก์ชัน isPerfect() รับ x:
    • sr := รากที่สองของ x
    • คืนค่า true เมื่อ (sr - floor ของ sr) เท่ากับ 0
  2. จากเมธอดหลัก:
    • ถ้า c เท่ากับ 0: คืนค่า true
    • for i := 0 ถึง ceiling ของรากที่สองของ c - 1 ทำ:
      • b := c - i * i
      • ถ้า isPerfect(b) เป็น true: คืนค่า true
    • คืนค่า false

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

#include <bits/stdc++.h> 
using namespace std; 

class Solution { 
public: 
    bool isPerfect(int x){ 
        long double sr = sqrt(x); 
        return ((sr - floor(sr)) == 0); 
    } 

    bool judgeSquareSum(int c) { 
        if (c == 0) 
            return true; 
        int b; 
        for (int i = 0; i < ceil(sqrt(c)); i++) { 
            b = c - i * i; 
            if (isPerfect(b)) 
                return true; 
        } 
        return false; 
    } 
}; 

int main(){ 
    Solution ob; 
    cout << (ob.judgeSquareSum(61)); 
}

อินพุต

61

เอาต์พุต

1