POJ2389 Bull Math(大数乘法)

题目链接

分析:

简单的大数乘法。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void multiply_big(char *a, char *b, char *c){//大数乘法
    int len1 = strlen(a), len2 = strlen(b), *s;
    int i, j;

    s = (int *)malloc(sizeof(int)*len1*len2);

    for(i=0; i<len1+len2; i++) s[i] = 0;

    for(i=0; i<len1; i++){
        for(j=0; j<len2; j++){
            s[i+j+1] += (a[i]-'0')*(b[j]-'0');
        }
    }

    for(i=len1+len2-1; i>=1; i--){
        if(s[i] >= 10){
            s[i-1] += s[i] / 10;
            s[i] %= 10;
        }
    }

    i=0;
    while(s[i] == 0) i++;
    for(j=0; i<len1+len2; i++, j++) c[j] = s[i] + '0';

    c[j] = '\0';

    free(s);
}

int dividor_big(char *a, int b, char *c){   //大数除法,这里除数并非大数,返回余数
    char *s;
    int tmp, i, j, len = strlen(a);

    s = (char *)malloc(sizeof(char)*(len+1));

    tmp = 0;
    for(i=0; i<len; i++){
        tmp = tmp*10+a[i]-'0';
        s[i] = tmp / b + '0';
        tmp %= b;
    }

    s[i] = '\0';
    for(i=0; s[i] == '0' && s[i] != '\0'; i++);

    if(s[i] == '\0'){
        c[0] = '0';
        c[1] = '\0';
    }
    else{
        for(j=0; i<len; i++, j++) c[j] = s[i];
        c[j] = '\0';
    }

    free(s);
    return tmp;
}

int main(){
    char a[1000], b[1000], c[1000];

    scanf("%s %s", a, b);
    multiply_big(a, b, c);
    printf("%s\n", c);

    return 0;
}
原文地址:https://www.cnblogs.com/tanhehe/p/2972210.html