裴蜀定理(又称贝祖定理)

特殊性: 对于方程ax+by=1只有整数a和b互质时,方程才有整数解。
扩展欧几里德算法是用来在已知a , b 求解一组x , y ,使它们满足裴蜀(贝祖)等式: a x + b y = gcd ( a , b ) = d
扩展欧几里得算法——exgcd
877. 扩展欧几里得算法

https://www.acwing.com/problem/content/description/879/

#include
#include
using namespace std; int exgcd(int a,int b,int &x, int &y) {
if(!b) {
x=1,y=0; return a; } int d=exgcd(b,a%b,y,x); y=y-a/b*x; return d; } int main(void) {
int t; cin>>t; while(t--) {
int a,b,x,y; cin>>a>>b; exgcd(a,b,x,y); cout<<x<<" "<<y<<endl; } return 0; }
#include
using namespace std; int exgcd(int a,int b,int& x,int& y) {
if(!b) return x=1,y=0,a; int d=exgcd(b,a%b,y,x); y=y-a/b*x; return d; } int main(void) {
int n; cin>>n; while(n--) {
int a,b,x,y; cin>>a>>b; exgcd(a,b,x,y); cout<<x<<" "<<y<<endl; } return 0; }
878. 线性同余方程

https://www.acwing.com/problem/content/880/

这不就是裴蜀定理么? 我们知道1可以用扩展的欧几里得来求解。如同上面的是一样。
但是我们这里是 b。 我们可以先求 ax+my=gcd(a,m) 最后在乘以一个倍数就可以了。
#include
#include
#include
using namespace std; typedef long long int LL; LL exgcd(LL a,LL b,LL &x,LL &y) {
if(!b){
x=1,y=0; return a; } int d=exgcd(b,a%b,y,x); y=y-a/b*x; return d; } int main(void) {
int t; cin>>t; while(t--) {
LL a,b,m; cin>>a>>b>>m; LL x,y,d; d=exgcd(a,m,x,y); if(b%d) cout<<"impossible"<<endl; else cout<<x*b/d%m<<endl; } return 0; }
#include
using namespace std; typedef long long int LL; LL exgcd(LL a,LL b,LL &x,LL &y) {
if(!b) return x=1,y=0,a; int d=exgcd(b,a%b,y,x); y=y-a/b*x; return d; } int main(void) {
int n; cin>>n; while(n--) {
LL a,b,m,x,y,d; cin>>a>>b>>m; d=exgcd(a,m,x,y); if(b%d) puts("impossible"); else cout<<x*b/d%m<<endl; } return 0; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/216637.html原文链接:https://javaforall.net
