-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbigNum3.c
138 lines (129 loc) · 2.37 KB
/
bigNum3.c
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <stdio.h>
#include <string.h>
#define PRECISION 60
typedef struct
{
int length;
int sign;
char value[PRECISION];
} bigInt;
void zeroInit(bigInt *tgt, int digits)
{
for (int i = 0; i < digits; i++)
{
tgt->value[i] = 0;
}
}
bigInt createBigInt(void)
{
bigInt a;
a.length = 0;
a.sign = 0;
return a;
}
bigInt readBigInt(void)
{
bigInt result = createBigInt();
char input[PRECISION + 2];
// char len;
scanf("%s", &input);
if (input[0] == '-')
{
result.sign = 1;
result.length = strlen(input) - 1;
for (int i = 0; i < result.length; i++)
{
result.value[i] = input[result.length - i] - '0';
}
}
else
{
result.length = strlen(input);
for (int i = 0; i < result.length; i++)
{
result.value[i] = input[result.length - i - 1] - '0';
}
}
return result;
}
void printBigInt(bigInt out)
{
if (out.sign)
{
putchar('-');
}
for (int i = out.length - 1; i >= 0; i--)
{
putchar(out.value[i] + '0');
}
}
bigInt bigAdd(bigInt a, bigInt b)
{
bigInt sum = createBigInt();
int lL, gL;
// Determine greater and lesser lengths.
if (a.length > b.length)
{
gL = a.length;
lL = b.length;
}
else
{
lL = a.length;
gL = b.length;
}
zeroInit(&sum, gL);
// Add a.
if (a.sign)
{
for (int i = 0; i < a.length; i++)
{
sum.value[i] -= a.value[i];
}
}
else
{
for (int i = 0; i < a.length; i++)
{
sum.value[i] += a.value[i];
}
}
// Add b.
if (b.sign)
{
for (int i = 0; i < b.length; i++)
{
sum.value[i] -= b.value[i];
}
}
else
{
for (int i = 0; i < b.length; i++)
{
sum.value[i] += b.value[i];
}
}
// Process carry
for (int i = 0; i < PRECISION; i++)
{
if (sum.value[i] > 9)
{
sum.value[i] -= 10;
sum.value[i + 1] += 1;
}
}
for (int i = PRECISION - 1; i >= 0; i--)
{
if (sum.value[i] < 0)
{
sum.value[i] -= 10;
sum.value[i + 1] += 1;
}
}
}
int main(void)
{
bigInt a = readBigInt();
printBigInt(a);
return 0;
}