首先说明,自己写的源代码不一定为最优解,只是我平时用的方法,如果有人能给出更好的建议,可以在下方评论,借鉴一下~
目录
数据定义
(cnt为整数位数,v存储着每一位的值,sign表示符号 )
typedef struct{int cnt,v[501],sign;}BIGINT;
//要注意,v中存放数值是从数字的个位开始倒序存放的,是为了后续的计算方便。
常见输入数据转换(int,char*)
//int转换成BIGINT
BIGINT int2BIG(int x) //int 转换成BIGINT
{
BIGINT R= {0,{0},1};
if(x<0){R.sign=-1;x=-x;}
do
{
R.v[R.cnt++]=x%10;
x/=10;
} while (x>0);
return R;
}
//char*转换成BIGINT
BIGINT char2BIG(char* s)
{
int len=strlen(s);
BIGINT R={len,{0},1};
int i=len-1,j=0;
if (s[0]=='-') {R.sign=-1;R.cnt=len-1;}
while(i>=0&&s[i]!='-')
{
R.v[j++]=s[i]-'0';
i--;
}
return R;
}
加法运算
//当涉及符号不一样时 ,就要转变为大整数的减法运算
BIGINT BIGADD(BIGINT s,BIGINT t)
{
if(s.cnt==0) return t;
if(t.cnt==0) return s;
BIGINT R={0,{0},1};
if(s.sign*t.sign<0)
{
if(s.sign==-1) R=BIGSUB(t,s);
else R=BIGSUB(s,t);
}
else
{
R.sign =s.sign;
int i,carry=0;
for(i=0 ;i<s.cnt&&i<t.cnt;i++)
{
int temp = s.v[i]+t.v[i]+carry;
R.v[i]=temp%10;
carry=temp/10;
}
while(i<t.cnt)
{
int temp =t.v[i]+carry;
R.v[i++] =temp%10;
carry = temp/10;
}
while (i<s.cnt)
{
int temp =s.v[i]+carry;
R.v[i++]=temp%10;
carry = temp/10;
}
if(carry)
{
R.v[i++]=carry%10;
}
R.cnt=i;
}
return R;
}
减法运算
int cmp(BIGINT s,BIGINT t)
{
int n =(s.cnt>t.cnt)?s.cnt:t.cnt;
for(int i=n-1;i>=0;i--)
{
if(*(s.v+i)>*(t.v+i)) return 1;
else if(*(s.v+i)<*(t.v+i)) return -1;
}
return 0;
}
void SUB(BIGINT* s,BIGINT* t,BIGINT* result)
{
int n=(s->cnt>t->cnt)?s->cnt:t->cnt;
result->cnt=n;
int carry=0,i;
for(i=0;i<n;i++)
{
if((*(s->v+i)+carry)<(*(t->v+i)))
{
*(result->v+i)=*(s->v+i)+10+carry-*(t->v+i);
carry=-1;
}
else {
*(result->v+i)=*(s->v+i)+carry-*(t->v+i);
carry=0;
}
}
for (int i=n-1;i>=0&&result->v[i]==0;i--) result->cnt--;
}
BIGINT BIGSUB (BIGINT s,BIGINT t)
{
BIGINT R={0,{0},1};
if (cmp(s,t)>=0)
{
R.sign=1;
SUB(&s,&t,&R);
}
else
{
R.sign=-1;
SUB(&t,&s,&R);
}
return R;
}
乘法运算
BIGINT BIGMUL(BIGINT S,BIGINT T)
{
BIGINT R={0,{0},1};
if(S.cnt==0||T.cnt==0) return R;
R.cnt = S.cnt+T.cnt;
R.sign =S.sign*T.sign;
for(int i=0;i<T.cnt;i++)
{
int j,t,k;
int carry=0;
for(j=0;j<S.cnt;j++)
{
t=S.v[j]*T.v[i]+carry+R.v[i+j];
R.v[i+j] = t%10;
carry=t/10;
}
k=i+j;
while (carry>0)
{
t=carry+R.v[k];
R.v[k]=t%10;
carry=t/10;
k++;
}
}
if (R.v[S.cnt+T.cnt-1]==0) R.cnt--;
return R;
}
输出函数
void BIGoutput(BIGINT x)
{
if(x.sign==-1) printf("-");
for(int i=x.cnt-1;i>=0;i--) printf("%d",x.v[i]);
}