大數乘法

題目

編寫兩個任意位數的大數相乘的程序,給出計算結果。

分析

            3   4   5       
        ×   6   7   8
----------------------      個位在左
            24  32  40      (5, 4, 3) × 8 = (40, 32, 24)
        21  28  35          (5, 4, 3) × 7 = (35, 28, 21)
    18  24  30              (5, 4, 3) × 6 = (30, 24, 18)
----------------------
    18  45  82  67  40      結果錯位相加
----------------------
                71  0       40取0, 進4, 67 + 4 = 71
            89  1           71取1, 進7, 82 + 7 = 89
        53  9               89取9, 進8, 45 + 8 = 53
    23  3                   53取3, 進5, 18 + 5 = 23
2   3                       23取3, 進2, 0 + 2 = 2
2                           2取2, 不進位
----------------------
2   3   3   9   1   0       計算結果

代碼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* toChar(char* a, int len)
{
    char* c = (char*)malloc(len - 1);
    for(int i = len - 2, j = 0; i >= 0; i--, j++) {
        c[j] = a[i] - '0';
    }
    return c;
}

int main()
{
    char a[] = "12341111";
    char b[] = "56781111";
    char* ap = toChar(a, sizeof(a));
    char* bp = toChar(b, sizeof(b));
    int ap_len = sizeof(a) - 1;
    int bp_len = sizeof(b) - 1;
    int cp_len = ap_len + bp_len;
    char* cp = (char*)malloc(cp_len);
    memset(cp, 0, ap_len + bp_len);
    // compute
    for(int i = 0; i < ap_len; i++) {
        for(int j = 0; j < bp_len; j++) {
            cp[i + j] += ap[i] * bp[j];
        }
    }

    for(int i = 0, p = 0; i < cp_len; i++) {
        cp[i] += p;
        p = cp[i] > 9 ? cp[i] / 10 : 0;
        cp[i] %= 10;
    }
    // print out
    int len = cp_len - 1;
    while(cp[len] == 0)
        len--;
    for(int i = len; i >= 0; i--) {
        printf("%d", cp[i]);
    }                                     //700741993554321
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章