题目传送门:https://www.lydsy.com/JudgeOnline/problem.php?id=1876
一道简单的高精度+Stein算法(或者叫辗转相除法)求最大公约数板子题。
md还要压位。。
代码:
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#define ll long long
#define ull unsigned long long
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define lowbit(x) (x& -x)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define eps 1e-18
#define maxn 100010
inline ll read(){ll tmp=; char c=getchar(),f=; for(;c<''||''<c;c=getchar())if(c=='-')f=-; for(;''<=c&&c<='';c=getchar())tmp=(tmp<<)+(tmp<<)+c-''; return tmp*f;}
inline ll power(ll a,ll b){ll ans=; for(;b;b>>=){if(b&)ans=ans*a%mod; a=a*a%mod;} return ans;}
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline void swap(int &a,int &b){int tmp=a; a=b; b=tmp;}
using namespace std;
const int base=;
struct Bignum{
int len;
int num[];
friend bool operator < (Bignum a,Bignum b){
if(a.len!=b.len)return a.len<b.len;
for(int i=a.len;i;i--)
if(a.num[i]!=b.num[i])return a.num[i]<b.num[i];
return ;
}
friend Bignum operator - (Bignum a,Bignum b){
Bignum c;
memset(&c,,sizeof(c));
for(int i=;i<=a.len;i++){
if(a.num[i]<b.num[i])a.num[i]+=base,--a.num[i+];
c.num[i]=a.num[i]-b.num[i];
}
c.len=a.len;
while(c.len>&&!c.num[c.len])--c.len;
return c;
}
friend Bignum operator * (Bignum a,int b){
Bignum c;
memset(&c,,sizeof(c)); ll tmp=;
for(int i=;i<=a.len;i++){
tmp+=a.num[i]*b;
c.num[i]=tmp%base; tmp/=base;
}
c.len=a.len;
for(;tmp;tmp/=base)c.num[++c.len]=tmp%base;
return c;
}
friend Bignum operator / (Bignum a,int b){
Bignum c;
memset(&c,,sizeof(c)); ll tmp=;
for(int i=a.len;i;i--){
tmp=tmp*base+a.num[i];
c.num[i]=tmp/b; tmp%=b;
}
c.len=a.len;
while(c.len>&&!c.num[c.len])--c.len;
return c;
}
void print(Bignum a){
printf("%d",a.num[a.len]);
for(int i=a.len-;i;i--)
printf("%09d",a.num[i]);
printf("\n");
}
}a,b;
char A[],B[];
int n,m;
Bignum gcd(Bignum a,Bignum b)
{
int cnt=;
while(){
if(a<b){
Bignum tmp; tmp=a; a=b; b=tmp;
}
if(b.len==&&b.num[]==)break;
if(a.num[]&){
if(b.num[]&){
Bignum tmp; tmp=b; b=a-b; a=tmp;
}
else b=b/;
}
else{
if(b.num[]&)a=a/;
else ++cnt,a=a/,b=b/;
}
}
Bignum ans=a;
for(int i=;i<=cnt;i+=)ans=ans*(<<);
for(int i=cnt%;i;i--)ans=ans*;
return ans;
}
int main()
{
scanf("%s",A); n=strlen(A);
scanf("%s",B); m=strlen(B);
a.len=b.len=;
for(int i=n-;i>=;i-=){
a.num[++a.len]=;
for(int j=max(i-,);j<=i;j++)
a.num[a.len]=a.num[a.len]*+A[j]-'';
}
for(int i=m-;i>=;i-=){
b.num[++b.len]=;
for(int j=max(i-,);j<=i;j++)
b.num[b.len]=b.num[b.len]*+B[j]-'';
}
Bignum ans=gcd(a,b);
ans.print(ans);
}
bzoj1876