-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbignum.c
executable file
·152 lines (140 loc) · 2.54 KB
/
bignum.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#include "bignum.h"
#include "accessor.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void clearByZero(struct NUMBER* a)
{
int i;
for (i = 0; i < KETA; i++)
{
a->n [i] = 0;
}
setSign (a, POSITIVE);
}
void setRnd (struct NUMBER* a, int n)
{
int i;
if (n < 0 || 30 < n)
printf("Out of range.");
else
{
for (i = 0; i < KETA; i++)
{
if (i < n)
a->n[i] = random()%10;
else
a->n[i] = 0;
}
if( random()%2 )
setSign (a, POSITIVE);
else
setSign (a, NEGATIVE);
}
}
void copyNumber(const struct NUMBER* a, struct NUMBER* b)
{
int i;
setSign(b, getSign(a));
for (i = 0; i < KETA; i++)
b->n[i] = a->n[i];
}
void getAbs(const struct NUMBER* a, struct NUMBER* b)
{
copyNumber(a, b);
setSign(b, POSITIVE);
}
int isZero (const struct NUMBER* a)
{
int i;
for (i = 0; i < KETA; i++)
{
if (a->n[i] != 0)
return (-1);
}
return (0);
}
void swap (struct NUMBER* a, struct NUMBER* b)
{
struct NUMBER c;
copyNumber(a, &c);
copyNumber(b, a);
copyNumber(&c, b);
}
int setInt (struct NUMBER* a, int x)
{
int mod, i = 0;
clearByZero (a);
if (x < 0)
{
setSign(a, -1);
x *= -1;
}
while (x > 0)
{
mod = x % 10;
x -= mod;
x /= 10;
a->n[i++] = mod;
if (i > KETA)
return -1;
}
return 0;
}
int numComp (const struct NUMBER* a, const struct NUMBER* b)
{
int i;
if (getSign(a) == POSITIVE && getSign(b) == NEGATIVE)
return 1;
else if (getSign(a) == NEGATIVE && getSign(b) == POSITIVE)
return -1;
else if (getSign(a) == POSITIVE && getSign(b) == POSITIVE)
{
for (i = 0; i < KETA; i++)
{
if (a->n[KETA-i-1] > b->n[KETA-i-1])
return 1;
else if (a->n[KETA-i-1] < b->n[KETA-i-1])
return -1;
}
return 0;
}
else if (getSign(a) == NEGATIVE && getSign(b) == NEGATIVE)
{
for (i = 0; i < KETA; i++)
{
if (a->n[KETA-i-1] > b->n[KETA-i-1])
return -1;
else if (a->n[KETA-i-1] < b->n[KETA-i-1])
return 1;
}
return 0;
}
return (-1);
}
int isEven (const struct NUMBER* number)
{
if (number->n[0]%2 == 0)
return 1;
else if (number->n[0]%2 == 1)
return 0;
return -1;
}
int getTopDigitIndex(const struct NUMBER* number)
{
int i;
for (i = KETA - 1; i >= 0; i--)
{
if (number->n[i] != 0)
break;
}
return i;
}
void copyPartition (const struct NUMBER* original, int firstIndex, int lastIndex, struct NUMBER* copied)
{
int i;
for (i = firstIndex; i >= lastIndex; i--)
{
copied->n[i-lastIndex] = original->n[i];
}
}