50021. Polynomial
難度:3/5
這題我寫得有點醜,有時間再改。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95/*
typedef struct Polynomial{
int degree;
int coff[4096];
}Polynomial;
*/
#include "polynomial.h"
#include <stdio.h>
#include <stdlib.h>
int max_func(int a, int b){
if(a > b) return a;
else return b;
}
void init(Polynomial *poly, int coefficient[], int n){
poly->degree = n - 1;
for(int i = 0; i < n; i++){
poly->coff[i] = coefficient[i];
}
for(int i = n + 1; i < 4096; i++){
poly->coff[i] = 0;
}
}
Polynomial add(Polynomial *poly1, Polynomial *poly2){
int coff[4096] = {0};
for(int i = 0; i < 4096; i++){
coff[i] = poly1->coff[i] + poly2->coff[i];
}
int max_deg;
for(int i = 4095; i >= 0; i--){
if(coff[i] != 0){
max_deg = i;
break;
}
}
max_deg = max_func(max_deg, 0);
Polynomial ans;
ans.degree = max_deg;
for(int i = 0; i < 4096; i++){
ans.coff[i] = coff[i];
}
return ans;
}
Polynomial multiply(Polynomial *poly1, Polynomial *poly2){
int coff[4096] = {0};
for(int i = 0; i <= poly1->degree; i++){
for(int j = 0; j <= poly2->degree; j++){
coff[i + j] += poly1->coff[i] * poly2->coff[j];
}
}
int max_deg;
for(int i = 4095; i >= 0; i--){
if(coff[i] != 0){
max_deg = i;
break;
}
}
max_deg = max_func(max_deg, 0);
Polynomial ans;
ans.degree = max_deg;
for(int i = 0; i < 4096; i++){
ans.coff[i] = coff[i];
}
return ans;
}
void print(Polynomial *poly){
for(int i = poly->degree; i >= 0; i--){
if(poly->coff[i] == 0) continue;
else{
if(i >= 2){
printf("%+dx^%d", poly->coff[i], i);
}
else if(i == 1){
printf("%+dx", poly->coff[i]);
}
else if(i == 0){
printf("%+d", poly->coff[i]);
}
}
}
printf("\n");
}