《编程思维与实践》1068.高次方数的尾数
题目
思路
没啥难度,直接复用计算a的n次方的代码即可,只需注意不足N位需要补0即可.
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 9001
typedef struct{int cnt,v[N];}BIGINT;
BIGINT carry(BIGINT S,int bin); //进位 bin表示进制 binary
BIGINT int2BIG(int x,int bin); //int 转换(to)成BIGINT
BIGINT mul(BIGINT S, BIGINT T) ; //两个大整数相乘
BIGINT pow(BIGINT a, int n) ; //计算 a的n次方
int main()
{
int T;
scanf("%d",&T);
for(int t=0;t<T;t++)
{
char s[11];
int B,n;
scanf("%s%d%d",s,&B,&n);
BIGINT A={strlen(s),{0}};
for(int i=0;i<strlen(s);i++) //逆向存
{
A.v[A.cnt-1-i]=s[i]-'0';
}
printf("case #%d:\n",t);
BIGINT ans=pow(A,B);
for(int i=n-1;i>=0;i--)
{
if(i>ans.cnt-1) //不足n位补0
{
printf("0");
}
else
{
printf("%d",ans.v[i]);
}
}
printf("\n");
}
return 0;
}
BIGINT carry(BIGINT S,int bin) //进位 bin表示进制 binary
{
int flag=0;
for(int i=0;i<S.cnt;i++)
{
int temp=S.v[i]+flag;
S.v[i]=temp%bin;
flag=temp/bin;
}
return S;
}
BIGINT int2BIG(int x,int bin) //int 转换(to)成BIGINT
{
BIGINT R={0,{0}};
do
{
R.v[R.cnt++]=x%bin;
x/=bin;
}while(x>0);
return R;
}
BIGINT mul(BIGINT S, BIGINT T) //两个大整数相乘
{
BIGINT R={S.cnt+T.cnt,{0}}; //位数最多为两者相加
for(int i=0;i<T.cnt;i++)
{
for (int j=0;j<S.cnt;j++)
{
R.v[i+j]+=S.v[j]*T.v[i]; //依此进行普通乘法
}
}
R=carry(R,10);
while(R.v[R.cnt-1]==0&&R.cnt>1)
{
R.cnt--; //最高位0不统计在一个大整数的位数中
}
return R;
}
BIGINT pow(BIGINT a, int n) //计算 a的n次方
{
BIGINT r;
if(n==0)
{
return int2BIG(1,10);
}
else if(n==1)
{
return a;
}
r=pow(a, n/2);
r=mul(r,r);
if(n%2!=0) //非偶数 需要多乘一个a
{
r=mul(r, a);
}
return r;
}