C++ 大数字的商和余数程序
给定一个字符串 num 来表示一个大数字,再给定一个大数字 m;任务是打印使用除法运算获得的商和使用取模获得大数字的余数。
输出应该是 余数 = xxx;商 = yyy
假设我们的输入 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 找到它的 mod。
- 通过 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
广告