大数(长长以上)和单个整数之间的除法
Division between a large numbers (Above long long) and a single integer
我正在尝试按照标题中的建议将数字除以整数,但我很难这样做。我正在考虑将大数字的数字插入向量中,然后从向量中反复减去所述数字,直到它为零。但是,我找不到执行此操作的代码。这是我到目前为止一直在尝试的:
#include <fstream>
using namespace std;
int v[100],r[100]; //In v i store the initial number,in r i store the result
int main()
{
FILE*fin=fopen("imp.in","r");
FILE*fout=fopen("imp.out","w");
int n,x,c,w,k,m=2;
fscanf(fin,"%d",&n); //Reads the number of digits the number has
for(;n>0;--n)
{
fscanf(fin,"%d",&x);
v[n]=x;
}
fscanf(fin,"%d",&c); //Reads the digit it has to be divided by
while(v[n]!=0)
{
k=0;
while(v[1]>=c)
{
v[1]-=c;
++k;
}//As long as the first position in vector can be substracted, increase k
--v[2];
v[1]+=10;
/* Because first position will be negative, take one from second position and add ten in the first*/
w=2;
while(v[w]<0)
{
v[w]=9;
--v[w+1];
++w;
}
/*When, for example, you substract one from 1000,it will become 999. This loop helps do that*/
r[1]+=k;
if(r[1]>9)
{
r[1]-=10;
w=2;
++r[2];
while(r[w]>9)
{
++r[w+1];
r[w]=0;
++w;
if(w>m)m=w;
}
}
/*If statement and the line of code above it inserts the result into r[100]*/
}
for(;w>0;--w)fprintf(fout,"%d",r[w]);
return 0;
}
您可以使用GMP,而不是从头开始自己编写。下载GMP源代码,构建它并学习如何使用它所花费的时间将比自己编写它所花费的时间更少。
以 2^32 或 2^64 为基数的铅笔和纸除法比"除以减法"更有效,我相信 GMP 采用比这更好的算法。
使用GMP,您可以编写:
mpz_class a("134897563047067890568704560457984059182035823590780968094759123590346040967804956029586405960249562895760983475187459073406984560900123895702851034560016405716045613495619456196450196450165901268051620465016405634056104951923845902387581");
std::cout << a / 7 << std::endl;
相关文章:
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 禁止指针和整数之间的比较C++
- Qt 错误 iso c++ 禁止指针和整数之间的比较 -permissive
- 递归函数,用于查找 2 个整数之间的最大值
- 如何包含整数之间的空格作为输出
- 在两个整数之间交换最右边的N位
- 打印出两个整数之间的偶数
- 定义整数之间的特殊划分
- 如何修复C++中的"指针和整数之间的比较"错误?
- 如何计算两个负整数 c++ 之间的总和
- 字符串和整数之间的模板冲突
- 如何在正整数和负整数之间进行匹配
- 将 OR 放入 if 语句会导致 ISO C++禁止指针和整数之间的比较(f 允许)
- C++无符号整数和无符号长整形整数之间的区别
- 错误(ISO C++禁止指针和整数之间的比较)[-fperemissive]
- ISO C++禁止指针和整数之间的比较
- 解释为 4 个字节的两个整数之间的计算范数
- 有符号整数和无符号整数之间的转换
- C 帮助(ISO C 禁止指针和整数之间的比较.)
- 高效实现 64 位和 32 位无符号整数之间的双向映射