2 bigint.c - Manage big positive integer numbers
3 Copyright (c) 1996,2001,5 Martin Schulze <joey@infodrom.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 bigint bigint_add(bigint a, bigint b)
30 unsigned long int tmp;
33 for (i=0; i<BIGINT_LEN; i++) {
34 tmp = a.val[i] + b.val[i];
35 if (tmp >= BIGINT_MAX) {
36 c.val[i] = tmp - BIGINT_MAX;
40 fprintf(stderr, "Overflow in bigint addition.\n");
47 bigint bigint_sub(bigint a, bigint b)
50 fprintf (stderr, "bigint_sub not supported yet.\n");
54 bigint bigint_int(int num)
59 for (i=0; i<BIGINT_LEN; i++) x.val[i] = 0L;
63 x.val[0] = num-BIGINT_MAX;
64 x.val[1] = num/BIGINT_MAX;
70 bigint bigint_string(char *s)
72 char tmp[BIGINT_PREC+1];
77 for (i=0; i<BIGINT_LEN; i++) a.val[i] = 0L;
78 if ((x = (char *)malloc(strlen(s)+1))) {
80 for (i=0; i<BIGINT_LEN; i++) {
83 if (strlen(x) > BIGINT_PREC)
84 cp += (strlen(x) - BIGINT_PREC);
87 sscanf(tmp, "%lu", &a.val[i]);
96 void bigint_sprintf (char *res, char *format, bigint a)
98 char s[(BIGINT_PREC*BIGINT_LEN)+1];
99 char tmp[BIGINT_PREC+1];
103 memset (s, 0, sizeof(s));
104 sprintf(form, "%%0%dlu", BIGINT_PREC);
106 for (;max>0 && !a.val[max-1];max--);
107 if (max == 0) s[0] = '0';
108 for (i=0; i<max; i++) {
110 sprintf(tmp, form, a.val[i]);
112 sprintf(tmp, "%lu", a.val[i]);
113 sprintf (res, "%s%s", tmp, s);
114 sprintf (s, "%s", res);
116 sprintf (res, format, s);