Data_Structure/作業/unit2/polynominal.c
2025-01-20 21:30:53 +08:00

88 lines
2.0 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <stdlib.h>
#define DUMMY -1
void output_P(int P[], int size);
void Padd(int A[], int B[], int C[]);
char compare(int a, int b);
void output_P(int P[], int size) {
int i;
int first = 1;
for (i = 2; i < size; i += 2) {
if (P[i+1] != 0) {
if (!first) {
printf(" + ");
}
if (P[i] > 1) {
printf("%dx^%d", P[i+1], P[i]);
} else if (P[i] == 1) {
printf("%dx", P[i+1]);
} else {
printf("%d", P[i+1]);
}
first = 0;
}
}
if (first) { // 如果多項式為0
printf("0");
}
printf("\n");
}
void Padd(int A[], int B[], int C[]) {
int i = 2, j = 2, k = 2;
int sizeA = A[1], sizeB = B[1];
while (i < sizeA * 2 + 2 || j < sizeB * 2 + 2) {
if (i >= sizeA * 2 + 2) {
C[k] = B[j];
C[k+1] = B[j+1];
j += 2;
} else if (j >= sizeB * 2 + 2) {
C[k] = A[i];
C[k+1] = A[i+1];
i += 2;
} else if (A[i] > B[j]) {
C[k] = A[i];
C[k+1] = A[i+1];
i += 2;
} else if (A[i] < B[j]) {
C[k] = B[j];
C[k+1] = B[j+1];
j += 2;
} else {
C[k] = A[i];
C[k+1] = A[i+1] + B[j+1];
if (C[k+1] == 0) {
k -= 2; // 如果係數為0不添加這一項
}
i += 2;
j += 2;
}
k += 2;
}
C[1] = (k - 2) / 2;
C[0] = DUMMY;
printf("A: ");
output_P(A, sizeA * 2 + 2);
printf("B: ");
output_P(B, sizeB * 2 + 2);
printf("C = A + B: ");
output_P(C, k);
}
char compare(int a, int b) {
if (a > b) return '>';
if (a < b) return '<';
return '=';
}
int main() {
int A[] = { DUMMY, 4, 4, 5, 3, 2, 2, 3, 0, 2 };
int B[] = { DUMMY, 3, 3, 6, 1, 5, 0, 1 };
int C[13] = { DUMMY };
Padd(A, B, C);
return 0;
}