/* poly.c 計算機数学 B プログラム 1 多項式の和と積 */ #include /* 高々 15 次の多項式の係数を 0 次から順に並べる */ //static int data1[16] = {1,2,1,2,1,2,0,0,0,0,0,0,0,0,0,0}; //static int data2[16] = {3,1,3,1,3,1,0,0,0,0,0,0,0,0,0,0}; static int data1[16] = {-1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; static int data2[16] = {3,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* 多項式の構造体を定義する */ struct polynom { char var; // 変数の文字 int deg; // 次数,ただし deg 0 = -1 とする. int coef[16]; // coef[i] が i 次の係数 }; /* 関数の宣言 */ void xpoly(struct polynom *pf); void addpoly(struct polynom g, struct polynom h, struct polynom *pf); void multpoly(struct polynom g, struct polynom h, struct polynom *pf); int main () { int i; struct polynom f, g, h; for (i=0; i<16; i++) { g.coef[i] = data1[i]; h.coef[i] = data2[i]; } xpoly(&g); xpoly(&h); addpoly(g,h,&f); for (i=0; i<16; i++) { printf("%d ",f.coef[i]); } printf("\n"); multpoly(g,h,&f); for (i=0; i<16; i++) { printf("%d ",f.coef[i]); } printf("\n"); return 0; } /* 変数を x とし,次数を調べて記入する */ void xpoly(struct polynom *pf) { int i; pf->var = 'x'; for (i=15; i>=0; i--) { if (pf->coef[i]!=0) { pf->deg = i; return; } } pf->deg = -1; return; } /* 多項式 g, h の和を計算し,ポインタ pf を使い結果を f に入れる */ void addpoly(struct polynom g, struct polynom h, struct polynom *pf) { int i; if (g.var != h.var) { printf("error : polynomial variables are not same"); return; } for (i=0; i<16; i++) { pf->coef[i] = g.coef[i] + h.coef[i]; } xpoly(pf); return; } /* 多項式 g, h の積を計算し,ポインタ pf を使い結果を f に入れる */ void multpoly(struct polynom g, struct polynom h, struct polynom *pf) { int i, k, d, a, b; if (g.var != h.var) { printf("error : polynomial variables are not same"); return; } if ((d = g.deg + h.deg) > 15) { printf("error : degrees are too large"); return; } for (i=0; i<16; i++) { pf->coef[i] = 0; } for (k=0; k<=d; k++) { a = 0; if (k > g.deg) a = k - g.deg; b = k; if (k > h.deg) b = h.deg; for (i=a; i<=b; i++) { pf->coef[k] += g.coef[k-i] *h.coef[i]; } } pf->deg = d; pf->var = 'x'; return; }