#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_LNUM_SIZE
32
#define DUMP_LNUM
1
#if DUMP_LNUM
static void dump_lnum_buf(const char *comment, char *lnum)
{
int i;
printf("%s: ", comment);
for (i=0; i<MAX_LNUM_SIZE; i++) {
printf("%2d ", lnum[i]);
}
printf("\n");
}
#endif
// handle carry of large number
static void lnum_carry(char *a)
{
int i, c = 0;
#if DUMP_LNUM
dump_lnum_buf("+lnum_carry", a);
#endif
for (i=MAX_LNUM_SIZE-1; i>=0; i--) {
a[i] += c;
c
= a[i] / 10;
a[i] %= 10;
}
#if DUMP_LNUM
dump_lnum_buf("-lnum_carry", a);
#endif
}
// a = a + (b <<< b_shift)
static void lnum_add(char *a, char *b, int b_shift)
{
int i, j;
#if DUMP_LNUM
dump_lnum_buf("+lnum_add a", a);
dump_lnum_buf("+lnum_add b", b);
#endif
for (i=0,j=b_shift; j<MAX_LNUM_SIZE; i++,j++) {
a[i] += b[j];
}
lnum_carry(a);
#if DUMP_LNUM
dump_lnum_buf("-lnum_add a", a);
#endif
}
static void lnum_to_string(char *str, char *lnum)
{
int i = 0;
int j = 0;
for (; i<MAX_LNUM_SIZE; i++) {
if (lnum[i]) break;
}
for (; i<MAX_LNUM_SIZE; i++) {
str[j++] = lnum[i] + '0';
}
str[j] = '\0';
}
void lnum_multiply(char *result, char *a, char *b)
{
char *lr = NULL;
char *lt = NULL;
int
nda= strlen(a);
int
ndb= strlen(b);
int
i, j;
lr = calloc(1, MAX_LNUM_SIZE);
lt = calloc(1, MAX_LNUM_SIZE);
if (!lr || !lt) {
printf("failed to allocate memory !\n");
goto exit;
}
if (nda < ndb) { // swap ta & tb
char *p;
int
t;
p = a; t
= nda;
a = b; nda = ndb;
b = p; ndb = t;
}
for (i=0; i<ndb; i++) {
for (j=0; j<nda; j++) {
lt[MAX_LNUM_SIZE - j - 1] = (a[nda-j-1] - '0') * (b[ndb-i-1] - '0');
}
lnum_add(lr, lt, i);
}
lnum_to_string(result, lr);
exit:
if (lr) free(lr);
if (lt) free(lt);
}
#if 1
int main(int argc, char *argv[])
{
char result[MAX_LNUM_SIZE] = {0};
if (argc < 3) {
printf("large number multiply program v1.0\n");
printf("written by rockcarry@\n");
printf("usage: multiply 123 456\n");
return 0;
}
lnum_multiply(result, argv[1], argv[2]);
printf("%s * %s = %s\n", argv[1], argv[2], result);
}
#endif
[此贴子已经被作者于2016-10-25 11:51编辑过]