扩展欧几里得 + 线性筛质因数

https://ac.nowcoder.com/acm/contest/5668/F
在这里插入图片描述

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

#define LL long long

int t;
LL a, b;

LL prime[2000010] = {0};
bool isPrime[2000010] = {0}; 
LL pfactor[2000010] = {0}; //质因数 

LL Gcd(int a, int b)
{
	if(b == 0) return a;
	return Gcd(b, a % b);
}

void getPrime(int n)
{
	int num = 0;
	for(int i = 1; i <= n; i++)
	{
		isPrime[i] = 1;
	}
	isPrime[1] = 0;
	pfactor[1] = 1;
	for(int i = 2; i<= n; i++)
	{
		if(isPrime[i])
		{
			prime[++num] = i;
			pfactor[i] = i;
		}
		for(int j = 1; j <= num && i * prime[j] <= n;j++)
		{
			isPrime[i * prime[j]] = 0;
			pfactor[i * prime[j]] = prime[j];
			if(i%prime[j]==0) break;
		}
	}
}

LL ex_Gcd(LL a, LL b, LL &x, LL &y)
{
	if(b == 0)
	{
		x = 1, y = 0;
		return a;
	}
	LL gcd = ex_Gcd(b, a % b, y, x);
	y -= (a / b) * x;
	return gcd;
}

int main()
{
	cin >> t;
	getPrime(2000001);
	while(t--)
	{
		cin >> a >> b;
		LL g = Gcd(a, b);
		if(g != 1)
		{
			cout << a / g + 1 << " " << b / g << " " << 1 << " " << b / g << endl;
			continue;
		}
		
		LL k = pfactor[b], d = 1, f = b;
		while(k != 1 && f % k == 0)
		{
			d *= k;
			f /= k;
		}
		
		if(f == 1)
		{
			cout << "-1 -1 -1 -1" << endl;
			continue;
		}
		
		LL c, e;
		ex_Gcd(d, f, e, c);
		e = -e;
		while(c <= 0 || e <= 0)
		{
			c += d;
			e += f;
		}
		c *= a;
		e *= a;
		cout << c << " " << d << " " << e << " " << f << endl;	
		
	}
	
	
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值