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

นับจำนวนธนบัตรที่ต้องใช้จ่ายเงิน (Coin Change แบบกำหนดจำนวนธนบัตร) ใน C++

โจทย์: ต้องจ่ายเงิน pay_Rupees โดยใช้ธนบัตร 2 ชนิดคือ Rupees_amount_1 และ Rupees_amount_2 จำนวนธนบัตรรวมต้องเท่ากับ distribution_total ต้องการหาจำนวนธนบัตรชนิดแรก

สมการทางคณิตศาสตร์

ให้ a = จำนวนธนบัตรชนิด 1, b = จำนวนธนบัตรชนิด 2

a + b = distribution_total
a×R₁ + b×R₂ = pay_Rupees

แทน b = N - a:

a×R₁ + (N-a)×R₂ = P
a(R₁ - R₂) = P - N×R₂
a = (P - N×R₂) / (R₁ - R₂)

เงื่อนไขมีคำตอบ

  • ตัวหาร (R₁ - R₂) ≠ 0
  • ตัวเศษ (P - N×R₂) หารตัวหารลงตัว
  • a ≥ 0 และ b = N - a ≥ 0

โค้ด C++

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

int notes_needed(int R1, int R2, int P, int N) {
    int numerator = P - (R2 * N);
    int denominator = R1 - R2;
    
    if (denominator == 0) return -1;  // ค่าเท่ากัน ไม่สามารถแก้ได้
    if (numerator % denominator != 0) return -1;  // ไม่หารลงตัว
    
    int count = numerator / denominator;
    if (count < 0 || count > N) return -1;  // จำนวนธนบัตรติดลบหรือเกิน
    
    return count;
}

int main() {
    int R1 = 1, R2 = 5, P = 11, N = 7;
    cout << "Count: " << notes_needed(R1, R2, P, N);
    return 0;
}

ผลลัพธ์

Count of number of currency notes needed are: 6

ตัวอย่างที่ 2

R1=2, R2=3, P=10, N=4
a = (10 - 3×4) / (2-3) = (10-12)/(-1) = 2
2 ใบ × 2 บาท + 2 ใบ × 3 บาท = 10 บาท ใช้ 4 ใบ ✓

กรณีไม่มีคำตอบ

R1=2, R2=4, P=7, N=3 → a = (7-12)/(2-4) = -5/-2 = 2.5 ไม่ใช่จำนวนเต็ม → return -1