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

จำนวนจุดจำนวนเต็มระหว่างสองจุดใน C++


หาจำนวนจุดจำนวนเต็ม (integral points) ระหว่างสองจุด

สูตร:

  • ทั่วไป: gcd(|x2-x1|, |y2-y1|) - 1
  • ขนานแกน x: |y1-y2| - 1
  • ขนานแกน y: |x1-x2| - 1

ตัวอย่าง:

Input: pointOne = [1, 5], pointTwo = [1, 3]
Output: 1

อัลกอริทึม

  • ถ้า x1 == x2: คืน |y1-y2| - 1
  • ถ้า y1 == y2: คืน |x1-x2| - 1
  • มิฉะนั้น: คืน gcd(|x1-x2|, |y1-y2|) - 1

การเขียนโปรแกรม C++

#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) {    if (b == 0) return a;    return gcd(b, a % b); } int getCount(int pointOne[], int pointTwo[]) {    if (pointOne[0] == pointTwo[0]) return abs(pointOne[1] - pointTwo[1]) - 1;    if (pointOne[1] == pointTwo[1]) return abs(pointOne[0] - pointTwo[0]) - 1;    return gcd(abs(pointOne[0] - pointTwo[0]), abs(pointOne[1] - pointTwo[1])) - 1; } int main() {    int pointOne[] = {1, 3}, pointTwo[] = {10, 12};    cout << getCount(pointOne, pointTwo) << endl;    return 0; }

ผลลัพธ์

8