DZ_14_1.1

 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
/*
Исправление: sum +=(n>j?arr1[j]:0)*(m>j?arr2[i-j]:0);
(было: sum +=(n>i?arr1[j]:0)*(m>i?arr2[i-j]:0);)
*/
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#define N 2
#define M 3
void printPolynom(int* arr, int n) {
if (n==0)
return;
if (arr[0] !=0)
printf("%i", arr[0]);
if (n > 1) {
if (arr[1] !=0) {
printf("%s%ix", (arr[1]>0 ? "+" : ""), arr[1]);
}
}
for (int i=2; i<n; i++) {
if (arr[i] !=0) {
printf("%s%ix^%i", (arr[i]>0 ? "+" : ""), arr[i], i);
}
}
printf("\n");
}
int* summPolynom(int* arr1, int* arr2, int n, int m) {
int* res = (int*)malloc((n>m?n:m)*sizeof(int));
if (n>m) {
for (int i=0; i<n; i++) {
res[i] = arr1[i] + (i<m ? arr2[i] : 0);
}
} else {
for (int i=0; i<m; i++) {
res[i] = arr2[i] + (i<n ? arr1[i] : 0);
}
}
return res;
}
int* multPolynom(int* arr1, int* arr2, int n, int m) {
int max = (n>m?n:m);
int* res = (int*)malloc(max*sizeof(int));
for (int i=0; i<max; i++) {
int sum=0;
for (int j=0; j<=i; j++) {
sum +=(n>j?arr1[j]:0)*(m>j?arr2[i-j]:0);
}
res[i] = sum;
}
return res;
}
int main() {
int polynomArr1[N] = { 4, 5 };
int polynomArr2[M] = { 2, 6, 8 };
int* newPol;
newPol = summPolynom(polynomArr1, polynomArr2, N, M);
printPolynom(newPol, N>M?N:M);
free(newPol);
newPol = multPolynom(polynomArr1, polynomArr2, N, M);
printPolynom(newPol, N>M?N:M);
free(newPol);
getch();
return 0;
}