高精度除以低精度.cpp
/*
高精度除以低精度,通常高精度算法掌握四部分(加法和乘法,減法,高精度除以低精度,高精度除以高精度)
由于除數(shù)是低精度的值,也就是說(shuō)除數(shù)沒(méi)有超出整型的數(shù)據(jù)范圍,雖然被除數(shù)是高精度,但是我們模擬豎式除法時(shí),從被除數(shù)取出的數(shù)是可以和除數(shù)直接作算術(shù)運(yùn)算的,
減下后的余數(shù)繼續(xù)模擬豎式除法的后續(xù)過(guò)程,直到我們完成整個(gè)豎式除法,因此商是高精度的值,而余數(shù)肯定是低精度的值
注意高精度的實(shí)現(xiàn)我們用結(jié)構(gòu)體,這樣方便我們的實(shí)現(xiàn)
*/
#include <bits/stdc++.h>
using namespace std;
typedef struct bignum
{
? ? ? ? int num[5005],l;/*num長(zhǎng)度視題目要求而定,各位數(shù)從0開(kāi)始存放,l表示數(shù)字的長(zhǎng)度*/
}BIGNUM,*PBIGNUM;
char tmp[5005];
BIGNUM Big_Div(const BIGNUM & a,int b,int & mod)/*a是高精度的被除數(shù),b是低精度的除數(shù),mod為余數(shù)同時(shí)也是輸出參數(shù),函數(shù)返回值為高精度商*/
{
? ? ? ? BIGNUM c;
? ? ? ? int i,j,s=0;
? ? ? ? c.l=0;
? ? ? ? for(i=a.l-1;i>=0;--i)
? ? ? ? {
? ? ? ? ? ? ? ? s=s*10+a.num[i];
? ? ? ? ? ? ? ? if(s<b)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? c.num[c.l++]=0;
? ? ? ? ? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? c.num[c.l++]=s/b;
? ? ? ? ? ? ? ? ? ? ? ? s%=b; ?
? ? ? ? ? ? ? ? } ? ? ?
? ? ? ? }
? ? ? ? mod=s;
? ? ? ? for(i=0,j=c.l-1;i<j;++i,--j)
? ? ? ? {
? ? ? ? ? ? ? ? swap(c.num[i],c.num[j]); ? ? ? ?
? ? ? ? }
? ? ? ? while(c.num[c.l-1]==0&&c.l>1)//高精度除以低精度中,無(wú)法確定高位在被減后的情況,所以從最高位開(kāi)始掃描,刪除前導(dǎo)0
? ? ? ? {
? ? ? ? c.l--;//高精度除以低精度中,乘積長(zhǎng)度-1
? ? ? ? }
? ? ? ? return c;
}
void Big_Read(BIGNUM & a,char s[])
{
? ? ? ? int i,j;
? ? ? ? memset(a.num,0,sizeof(a.num));
? ? ? ? a.l=strlen(s);
? ? ? ? for(i=0,j=a.l-1;i<a.l;++i,--j)//高精度除以低精度中,通過(guò)循環(huán)把s數(shù)組的值逆置保存到a.num數(shù)組中
? ? ? ? {
? ? ? ? ? ? ? ? a.num[i]=s[j]-'0';
? ? ? ? }
}
void Big_Print(const BIGNUM & a)
{
? ? ? ? int i;
? ? ? ? for(i=a.l-1;i>=0;--i)
? ? ? ? {
? ? ? ? ? ? ? ? printf("%d",a.num[i]);
? ? ? ? }
? ? ? ? printf("\n");
}
int main()
{
? ? ? ? BIGNUM a,c;
? ? ? ? int b,mod;
? ? ? ? gets(tmp);
? ? ? ? Big_Read(a,tmp);
? ? ? ? scanf("%d",&b);
? ? ? ? c=Big_Div(a,b,mod);
? ? ? ? Big_Print(c);
? ? ? ? //printf("%d",mod);
? ? ? ? return 0;
}