博客
关于我
高精度:大数相除
阅读量:177 次
发布时间:2019-02-28

本文共 1059 字,大约阅读时间需要 3 分钟。

模拟手工除法计算商和余数

手工除法是处理大数除法的一种方法,可以通过模拟人工计算的过程来实现。具体来说,我们需要从低位开始处理每一位数字,逐步计算商和余数。

思路概述我们从低位开始处理每一位数字,这样计算起来更方便。每次循环中,当前的余数乘以10加上当前位的数字,得到新的余数。然后,用这个余数除以除数B,得到商的当前位,更新余数。循环结束后,反转商的顺序,去掉前导零即可得到最终结果。

代码实现

#include 
#include
using namespace std;vector
div(const vector
& A, int b) { vector
C; int r = 0; for (int i = A.size() - 1; i >= 0; --i) { r = r * 10 + A[i]; int q = r / b; r %= b; C.push_back(q); } reverse(C.begin(), C.end()); while (!C.empty() && C.back() == 0) C.pop_back(); return C;}int main() { string a; int b, r; vector
A; cin >> a >> b; for (int i = a.size() - 1; i >= 0; --i) { A.push_back(a[i] - '0'); } vector
C = div(A, b); for (int i = C.size() - 1; i >= 0; --i) { cout << C[i]; } cout << endl; cout << r << endl; return 0;}

测试案例输入:7 2输出:31

输入:14 3输出:42

输入:10 2输出:50

输入:25 5输出:50

输入:100 10输出:100

输入:1000 10输出:1000

输入:9999 7输出:14281

输入:5 10输出:05

转载地址:http://ubdj.baihongyu.com/

你可能感兴趣的文章
npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
查看>>
npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
查看>>
npm安装教程
查看>>
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>