C++程序中将大数表示为字符串的除法
在本教程中,我们将学习如何对表示为字符串的大数进行除法。
我们得到了以字符串格式表示的大数和一个除数。我们的程序应该找到余数。
首先,我们将找到给定数字中大于被除数的部分。然后,我们将逐个将剩余的数字添加到除数。
让我们看看解决问题的步骤。
初始化大数以及除数。
迭代给定的数字,直到我们提取大于除数的部分。
现在,从我们在上一步结束的地方迭代到数字的末尾。
将提取的部分除以除数并将其添加到结果中。
使用下一个数字更新数字。
检查结果是否为零。
并打印结果。
示例
让我们看看代码。
#include <bits/stdc++.h>
using namespace std;
string divideLargeNumber(string number, int divisor) {
// to store the result
string result;
int index = 0;
// extracting the part that is greater than the given divisor
int dividend = number[index] - '0';
while (dividend < divisor) {
dividend = dividend * 10 + (number[++index] - '0');
}
// iterating until all digits participate in the division
while (number.size() > index) {
result += (dividend / divisor) + '0';
// adding the next digit to the dividend
dividend = (dividend % divisor) * 10 + number[++index] - '0';
}
if (result.length() == 0) {
return "0";
}
return result;
}
int main() {
string large_number = "12345678901234567890";
int divisor = 75;
cout << divideLargeNumber(large_number, divisor) << endl;
return 0;
}输出
如果您执行上述程序,则将获得以下结果。
164609052016460905
结论
如果您在本教程中遇到任何疑问,请在评论部分提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP