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

หา 2 Numbers ที่ Sum และ GCD กำหนดใน C++

มี Sum และ GCD ของ 2 Numbers a และ b ต้องหา a และ b ถ้าไม่ได้คืน -1 ตัวอย่าง Sum=6, GCD=2 ได้ Numbers 4 และ 2

แนวทาง: เนื่องจาก GCD กำหนด Numbers จะเป็น Multiples ของ GCD เลือกตัวแรก = GCD ตัวที่สอง = Sum - GCD ถ้าผลรวมตรงกับ Sum ที่ให้มา พิมพ์ทั้งคู่ มิฉะนั้น -1

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

#include <iostream>
#include <algorithm>
using namespace std;

void printTwoNumbers(int s, int g) {
    if (__gcd(g, s - g) == g && s != g)
        cout << "first number = " << min(g, s - g) << "\nsecond number = " << s - min(g, s - g) << endl;
    else
        cout << -1 << endl;
}

int main() {
    int sum = 6;
    int gcd = 2;
    printTwoNumbers(sum, gcd);
}

ผลลัพธ์

first number = 2 second number = 4