บทนำ
โปรแกรมนี้สาธิตวิธีทำการหาร (Division) โดยใช้แค่ตัวดำเนินการลบ (-) แทนการหาร (/) โดยตรง
หลักการทำงาน
การหาร a ÷ b สามารถทำได้โดยการลบ b ออกจาก a ซ้ำๆ จนกว่า a จะน้อยกว่า b จำนวนครั้งที่ลบได้คือ ผลหาร (Quotient)
ขั้นตอนการแก้ปัญหา
- รับค่า dividend (ตัวถูกหาร) และ divisor (ตัวหาร)
- จัดการกรณีหารด้วย 0 และ dividend เป็น 0
- กำหนดเครื่องหมายผลลัพธ์ (ลบหรือบวก)
- แปลงทั้งคู่เป็นค่าบวก
- วนลูปลบ divisor ออกจาก dividend นับจำนวนรอบ
- นำเครื่องหมายกลับมา
ตัวอย่างโค้ด
#include <bits/stdc++.h>
using namespace std;
int division(int num_one, int num_two) {
if (num_one == 0) {
return 0;
}
if (num_two == 0) {
return INT_MAX;
}
bool negative_result = false;
if (num_one < 0) {
num_one = -num_one;
if (num_two < 0) {
num_two = -num_two;
} else {
negative_result = true;
}
} else if (num_two < 0) {
num_two = -num_two;
negative_result = true;
}
int quotient = 0;
while (num_one >= num_two) {
num_one = num_one - num_two;
quotient++;
}
if (negative_result) {
quotient = -quotient;
}
return quotient;
}
int main() {
int num_one = 24, num_two = 5;
cout << division(num_one, num_two) << endl;
return 0;
}
ผลลัพธ์
4
ข้อจำกัด
วิธีนี้ใช้เวลา O(quotient) ซึ่งช้ามากถ้าผลหารใหญ่ (เช่น 10⁹ ÷ 1) วิธีที่ดีกว่าคือใช้ Bit Shifting (Binary Long Division) ที่เป็น O(log n)
สรุป
เข้าใจหลักการพื้นฐานของการหาร ช่วยให้เข้าใจว่า Hardware/ALU ทำงานอย่างไรในระดับต่ำ