plan9port

fork of plan9port with libvec, libstr and libsdb
Log | Files | Refs | README | LICENSE

mpadd.c (792B)


      1 #include "os.h"
      2 #include <mp.h>
      3 #include "dat.h"
      4 
      5 /* sum = abs(b1) + abs(b2), i.e., add the magnitudes */
      6 void
      7 mpmagadd(mpint *b1, mpint *b2, mpint *sum)
      8 {
      9 	int m, n;
     10 	mpint *t;
     11 
     12 	/* get the sizes right */
     13 	if(b2->top > b1->top){
     14 		t = b1;
     15 		b1 = b2;
     16 		b2 = t;
     17 	}
     18 	n = b1->top;
     19 	m = b2->top;
     20 	if(n == 0){
     21 		mpassign(mpzero, sum);
     22 		return;
     23 	}
     24 	if(m == 0){
     25 		mpassign(b1, sum);
     26 		return;
     27 	}
     28 	mpbits(sum, (n+1)*Dbits);
     29 	sum->top = n+1;
     30 
     31 	mpvecadd(b1->p, n, b2->p, m, sum->p);
     32 	sum->sign = 1;
     33 
     34 	mpnorm(sum);
     35 }
     36 
     37 /* sum = b1 + b2 */
     38 void
     39 mpadd(mpint *b1, mpint *b2, mpint *sum)
     40 {
     41 	int sign;
     42 
     43 	if(b1->sign != b2->sign){
     44 		if(b1->sign < 0)
     45 			mpmagsub(b2, b1, sum);
     46 		else
     47 			mpmagsub(b1, b2, sum);
     48 	} else {
     49 		sign = b1->sign;
     50 		mpmagadd(b1, b2, sum);
     51 		if(sum->top != 0)
     52 			sum->sign = sign;
     53 	}
     54 }