ให้เหล็กไนของตัวเลขใหญ่พูดว่า num และอีกจำนวนหนึ่งบอกว่า m; งานคือการพิมพ์ผลหารโดยใช้การดำเนินการหารและส่วนที่เหลือของตัวเลขจำนวนมากโดยใช้โมดูลัส
ผลลัพธ์ควรเป็น Remainder =xxx; Quotient =ปปปป
สมมติว่าเรามีอินพุต num =string num ="14598499948265358486" และอินพุตอื่น m =487 ดังนั้นส่วนที่เหลือคือ 430 และเชาวน์คือ 29976385930729688
ตัวอย่าง
Input: num = “214755974562154868” m = 17 Output: Remainder = 15 quotient = 12632704386009109 Input: num =“214” m = 5 Output: Remainder = 4 Quotient = 42
แนวทางที่เราจะใช้ในการแก้ปัญหาที่กำหนด −
- เริ่มต้นตั้งค่า mod เป็น 0
- เริ่มจากทางขวา เราต้องหาม็อดโดยใช้:mod =(mod * 10 + digit) % m.
- การหาผลหารด้วย quo[i] =mod/m โดยที่ i คือจำนวนตำแหน่งของผลหาร
อัลกอริทึม
Start Step 1 -> Declare long long ll Step 2 -> In function void quotientremainder(string num, ll m) Declare a vector<int> vec Set ll mod = 0 Loop For i = 0 and i < num.size() and i++ Set digit = num[i] - '0' Set mod = mod * 10 + digit Set quo = mod / m Call vec.push_back(quo) Set mod = mod % m End loop Print remainder value which is in mod Set zeroflag = 0 Loop For i = 0 and i < vec.size() and i++ If vec[i] == 0 && zeroflag == 0 then, Continue End If zeroflag = 1 print the value of vec[i] End For Return Step 3 -> In function int main() Declare and assign num = "14598499948265358486" Declare and assign ll m = 487 Call function quotientremainder(num, m) Stop
ตัวอย่าง
#include <bits/stdc++.h> using namespace std; typedef long long ll; // Function to calculate the modulus void quotientremainder(string num, ll m) { // Store the modulus of big number vector<int> vec; ll mod = 0; // Do step by step division for (int i = 0; i < num.size(); i++) { int digit = num[i] - '0'; // Update modulo by concatenating // current digit. mod = mod * 10 + digit; // Update quotient int quo = mod / m; vec.push_back(quo); // Update mod for next iteration. mod = mod % m; } cout << "\nRemainder : " << mod << "\n"; cout << "Quotient : "; // Flag used to remove starting zeros bool zeroflag = 0; for (int i = 0; i < vec.size(); i++) { if (vec[i] == 0 && zeroflag == 0) continue; zeroflag = 1; cout << vec[i]; } return; } // main block int main() { string num = "14598499948265358486"; ll m = 487; quotientremainder(num, m); return 0; }
ผลลัพธ์
Remainder : 430 Quotient : 29976385930729688