AcWing 794. 高精度除法

算法思路

模拟除法竖式。

流程

  1. 从最高位开始处理,上一次的余数 \(\times 10\) 再加上当前位上的数字(被除数,我们令它为 \(A\));
  2. 往答案数组中压入 \(\lfloor \frac{A}{B} \rfloor\)(这里 \(B\) 表示除数),然后将余数更新为 \(A \bmod B\)
  3. 重复以上操作。

代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;

vector<int> div(vector<int> &a, int b, int &r) //加上引用,方便直接传输余数
{
	int t = 0;
    vector<int> c;
    for (int i = a.size() - 1; i >= 0; i -- ) //从最高位开始处理
    {
    	r = r * 10 + a[i];
    	c.push_back(r / b);
    	r %= b;
	}
	reverse(c.begin(), c.end()); //反过来
	//处理前导0
    while (c.size() > 1 && c.back() == 0) c.pop_back();
    return c;
}

int main()
{
    string x;
    int b;
    cin >> x >> b;
    vector<int> a;
    for (int i = x.length() - 1; i >= 0; i -- ) a.push_back(x[i] - '0');
    int r;
    vector<int> c = div(a, b, r);
    for (int i = c.size() - 1; i >= 0; i -- ) printf("%d", c[i]);
    printf("\n%d", r);
    return 0;
}

\(\text {Python}\):高精是啥?我不懂!

a = input()
b = input()
print(a // b)
print(a % b)
posted @ 2022-07-29 20:16  FXT1110011010OI  阅读(49)  评论(0)    收藏  举报