1 /* Copyright (c) 2008 Jérémie Laval, Marine Jourdain
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to deal
5 * in the Software without restriction, including without limitation the rights
6 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 * copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 #include "biginteger.h"
29 #include "biginteger_utils.h"
32 BigInteger
sumBigInt(BigInteger b1
, BigInteger b2
)
34 // Check some sign conditions
35 // (-b1 + b2) <=> (b2 - (+b2))
36 if (b1
.Sign
== Negative
&& b2
.Sign
== Positive
) {
38 return diffBigInt(b2
, b1
);
40 // (b1 + (-b2)) <=> (b1 - (+b2))
41 if (b1
.Sign
== Positive
&& b2
.Sign
== Negative
) {
43 return diffBigInt(b1
, b2
);
46 BigInteger result
= CreateZeroBigInt();
48 if (b1
.Sign
== Negative
&& b2
.Sign
== Negative
)
49 result
.Sign
= Negative
;
51 result
.Sign
= Positive
;
53 BigUnsignedInteger
* node1
= b1
.AbsValStart
;
54 BigUnsignedInteger
* node2
= b2
.AbsValStart
;
62 unsigned int carry
= 0;
68 unsigned int newValue
= (node1
== NULL
? 0 : node1
->Value
) + (node2
== NULL
? 0 : node2
->Value
) + carry
;
70 carry
= newValue
/ BASE
;
71 newValue
= newValue
% BASE
;
72 PushEndNode(&result
, newValue
);
75 cont
= (node1
= node1
->Next
) != NULL
;
79 cont
= node2
!= NULL
|| cont
;
85 PushEndNode(&result
, carry
);