-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolynomial_diffrentiation.c
More file actions
87 lines (74 loc) · 1.62 KB
/
polynomial_diffrentiation.c
File metadata and controls
87 lines (74 loc) · 1.62 KB
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
// Find the differentiation of the polynomial equation using Singly Linked List.
// Input Format :
// First line contains the highest degree of the polynomial
// Second line contains the Coefficient of polynomial
// Sample Input :
// 5
// 3 0 -2 0 1 5
// Sample Output:
// 15x^4 - 6x^2 + 1x^0
// Explanation:
// Differentiation (3x^5 + 0x^4 - 2x^3 + 0x^2 + 1x^1 + 5x^0) = 15x^4 - 6x^2 + 1x^0
#include <stdio.h>
#include <stdlib.h>
struct node
{
int coeff;
int pow;
struct node *next;
};
typedef struct node node;
void insert(node *poly, int c, int x)
{
node *newnode = malloc(sizeof(node));
newnode->coeff = c;
newnode->pow = x;
newnode->next = NULL;
node *pos = poly;
while (pos->next != NULL)
{
pos = pos->next;
}
pos->next = newnode;
}
void diff(node *poly, node *result)
{
node *pos1 = poly;
node *pos2 = result;
while (pos1->next != NULL)
{
pos1 = pos1->next;
insert(result, pos1->coeff * pos1->pow, pos2->pow = pos1->pow - 1);
}
}
int main()
{
node *poly = malloc(sizeof(node));
node *result = malloc(sizeof(node));
poly->next = NULL;
result->next = NULL;
int n, x;
scanf("%d", &n);
int f = n + 1;
for (int i = 0; i < f; i++)
{
scanf("%d", &x);
if (x != 0)
{
insert(poly, x, n);
}
n--;
}
diff(poly, result);
node *pos = result;
while (pos->next->next != NULL)
{
pos = pos->next;
printf("%dx^%d", pos->coeff, pos->pow);
if (pos->next->coeff > 0)
{
printf(" + ");
}
}
return 0;
}