Binary GCD(高精)求助
查看原帖
Binary GCD(高精)求助
214728
剑雪清寒楼主2022/9/1 20:17

rt,代码中某些实现仅为需要,如&==的重载

已知会在两个大整数(其实也不大,甚至可能只有七八为)求GCD时,递归至两个小素数开始死循环,球球帮忙看下)))

#include <bits/stdc++.h>
using namespace std;
inline long long read() {
	long long x;bool f;char ch;
	for(f=0;!isdigit(ch=getchar());f=ch=='-');
	for(x=ch-48;isdigit(ch=getchar());x=x*10+ch-48);
	return f?-x:x;
}
inline void print(long long x,int len) {
	if(!x) {
		if(len) while(len--) putchar(48);
		else putchar(48);
		return ;
	}
	if(x<0) putchar('-'),x=-x;
	int ls[20],k=0;
	while(x) ls[++k]=x%10,x/=10;
	while(k<len) ls[++k]=0;
	while(k) putchar(ls[k--]+48);
	return ;
}
struct lint {
	int sum[2001],len=0;bool tag=true;
	inline bool operator==(const int &ls) const {
		if(!ls) {
			if(!len) return true;
			return false;
		}
	}
	inline int operator&(const int &ls) const {
		return sum[1]&ls;
	}
	inline bool operator>(const lint &ls) const {
		if(len>ls.len) return true;
		if(ls.len>len) return false;
		int now=len;
		while(now) {
			if(sum[now]>ls.sum[now]) return true;
			if(sum[now]<ls.sum[now]) return false;
			now--;
		}
		return false;
	}
	inline lint operator-(const lint &ls) const {
		lint a,b;bool tag=false;
		if(ls>*this) a=ls,b=*this;
		else a=*this,b=ls,tag=true;
		int now=len;
		while(now) {
			a.sum[now]-=b.sum[now];
			if(a.sum[now]<0) a.sum[now+1]--,a.sum[now]+=1e6;
			now--;
			while(!a.sum[a.len] && a.len) a.len--;
		}
		a.tag=tag;
		return a;
	}
	inline void output(char las) {
		if(!tag) putchar('-');
		if(!len) {
			putchar('0'),putchar(las);
			return ;
		}
		int now=len;
		print(sum[now],0);now--;
		while(now) {
			print(sum[now],5);now--;
		}
		putchar(las);
		return ;
	}
	/*inline void op(int k) {
		print(sum[k],5);
	}*/
	inline void init(string s) {
		int las=s.length()-1;
		for(int i=las,j=1;i>=0;j*=10,i--) {
			if(j>1e4) j=1;
			if(j==1) len+=1;
			sum[len]+=j*(s[i]-'0');
		}
		return ;
	}
	inline lint operator>>(const int&lence) {
		int now=len,lost=0,k=1<<lence;
		while(now) {
			sum[now]+=lost*1e5;
			lost=now%k;
			sum[now]>>=lence;
			if(!sum[len]) len--;
			now--;
		}
		return *this;
	}
	inline lint operator<<(const int&lence) {
		int now=0,lost=0;
		while(now<=len) {
			sum[now]<<=lence;
			lost=sum[now]/1e5;
			sum[now]%=(int)1e5;
			if(lost && now==len) len++;
			now++;
		}
		return *this;
	}
};
inline void init(lint &a) {
	string s;
	cin>>s;
	a.init(s);
	return ;
}
inline lint gcd(lint x,lint y) {
	x.output(' '),y.output('\n');
	if((x-y)==0) return x;
	if(x==0) return y;
	if(y==0) return x;
	if(x&1) {
		if(y&1) return x>y ? gcd((x-y)>>1,y) : gcd((y-x)>>1,x);
		else return gcd(x,y>>1);
	}
	if(y&1) return gcd(x>>1,y);
	else return gcd(x>>1,y>>1)<<1;
}
int main() {
	lint a,b;
	/*a.sum[1]=123;a.len=2;a.sum[2]=123;
	a.output('\n');*/
	init(a);init(b);
//	(a-b).output('\n');
	gcd(a,b).output('\n');
	return 0;
}

2022/9/1 20:17
加载中...