扩展欧几里得求两多项式最大公因式

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <math.h>

using namespace std;
typedef long long LL;
const double eps = 1e-8;
const int MOD = 999983;
const int N = 55;

struct Poly
{
    int n;
    LL a[N];
};

Poly p[25];

LL gcd(LL a,LL b)
{
    return b? gcd(b,a%b):a;
}

Poly delete_zero(Poly x)
{
    int i,j;
    Poly tmp;
    for(i=0;i<x.n && x.a[i] == 0;i++);
    for(j=0;i<x.n;i++,j++) tmp.a[j] = x.a[i];
    tmp.n = j;
    return tmp;
}

Poly poly_gcd(Poly x,Poly y)
{
    x = delete_zero(x);
    y = delete_zero(y);
    Poly yy = y,tmp;
    tmp.n = 0;
    int i=0;
    if(x.n == y.n)
    {
        double k = x.a[0] / y.a[0];
        for(i=1;i<x.n;i++)
            if(fabs(x.a[i]*1.0 - k*y.a[i]) > eps) break;
        if(i == x.n) return y;
    }
    LL g = gcd(x.a[0],y.a[0]);
    LL tx = y.a[0] / g;
    LL ty = x.a[0] / g;
    for(i=0;i<x.n;i++)
    {
        x.a[i] *= tx;
        x.a[i] %= MOD;
    }
    for(i=0;i<y.n;i++)
    {
        y.a[i] *= ty;
        y.a[i] %= MOD;
    }
    if(x.n < y.n) swap(x,y);
    for(i=1;i<y.n;i++)
        tmp.a[i-1] = ((x.a[i] - y.a[i])%MOD + MOD)%MOD;
    for(;i<x.n;i++)
        tmp.a[i-1] = x.a[i];
    tmp.n = x.n - 1;
    tmp = delete_zero(tmp);
    if(tmp.n == 0) return yy;
    return poly_gcd(y,tmp);
}

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值