เราได้รับจำนวนเต็มบวก N เป้าหมายคือนับคู่ของจำนวนเต็มบวกที่ไม่ซ้ำกัน (x, y) ที่ทำให้สมการ x² + y² < N เป็นจริง
เราจะเริ่มจาก x=0 ถึง x² < N และ y=0 ถึง y² < N หาก x² + y² < N ให้นับคู่นั้น
อินพุต
n = 4
เอาต์พุต
distinct pairs = 4
คำอธิบาย − คู่คือ (0,0), (1,1), (0,1), (1,0) ทุกคู่ทำให้ x² + y² < 4
อินพุต
n = 2
เอาต์พุต
distinct pairs = 3
คำอธิบาย − คู่คือ (0,0), (0,1), (1,0) ทำให้ x² + y² < 2
วิธีการที่ใช้ในโปรแกรมด้านล่าง
- จำนวนเต็ม N เก็บค่าอินพุต
- ฟังก์ชัน countPairs(int n) คืนค่าจำนวนคู่ที่ทำให้ x² + y² < n
- count เก็บจำนวนคู่ เริ่มต้น 0
- ลูป i=0 ถึง i² < n และ j=0 ถึง j² < n
- หาก i² + j² < n ให้เพิ่ม count
- คืนค่า count
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int countPairs(int n) {
int count = 0;
for (int i = 0; i*i < n; i++)
for (int j = 0; j*j < n; j++)
if (i*i + j*j < n)
count++;
return count;
}
int main() {
int N = 4;
cout << "Distinct Non-Negative integer pairs count: " << countPairs(N);
return 0;
}
ผลลัพธ์
Distinct Non-Negative integer pairs count: 4