UVA 10951 - Polynomial GCD(數論)

來源:互聯網
上載者:User

標籤:style   blog   http   color   2014   os   

UVA 10951 - Polynomial GCD

題目連結

題意:給定兩個多項式,求多項式的gcd,要求首項次數為1,多項式中的運算都%n,並且n為素數.

思路:和gcd基本一樣,只不過傳入的是兩個多項式,由於有%n這個條件,所以計算過程可以用乘法逆去計算除法模,然後最後輸出的時候每項除掉首項的次數就是答案了.

代碼:

#include <stdio.h>#include <string.h>#include <vector>using namespace std;int n;vector<int> f, g;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 -= a / b * x;    return d;}int inv(int a, int n) {    int x, y;    exgcd(a, n, x , y);    return (x + n) % n;}vector<int> pmod(vector<int> f, vector<int> g) {    int fz = f.size(), gz = g.size();    for (int i = 0; i < fz; i++) {int k = fz - i - gz;if (k < 0) break;int a = f[i] * inv(g[0], n) % n;for (int j = 0; j < gz; j++) {    int now = i + j;    f[now] = ((f[now] - a * g[j] % n) % n + n) % n;}    }    vector<int> ans;    int p = -1;    for (int i = 0; i < fz; i++) if (f[i] != 0) {p = i; break;}    if (p >= 0) for (int i = p; i < fz; i++) ans.push_back(f[i]);    return ans;}vector<int> gcd(vector<int> f, vector<int> g) {    if (g.size() == 0) return f;    return gcd(g, pmod(f, g));}int main() {    int cas = 0;    while (~scanf("%d", &n) && n) {f.clear(); g.clear();int a, k;scanf("%d", &a);for (int i = 0; i <= a; i++) {    scanf("%d", &k);    f.push_back(k);}scanf("%d", &a);for (int i = 0; i <= a; i++) {    scanf("%d", &k);    g.push_back(k);}vector<int> ans = gcd(f, g);int tmp = inv(ans[0], n), ansz = ans.size();;printf("Case %d: %d", ++cas, ansz - 1);for (int i = 0; i < ansz; i++) {    printf(" %d", ans[i] * tmp % n);}printf("\n");    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.