1. 程式人生 > >大整數運算練習

大整數運算練習

IV 交換 stdio.h com HA 乘法 compare can !=

#include<stdio.h>
#include<string.h>
struct bign {
    int d[1000];
    int len;
    bign() {   //構造函數(函數名和結構體相同, 無返回值)
        memset(d, 0, sizeof(d)); //頭文件<string.h>
        len = 0;
    }
};

bign change(char str[]) {   //字符串倒著賦給d[]數組
    bign a;
    a.len = strlen(str);
    for (int i = 0
; i < a.len; i++) { a.d[i] = str[a.len - i - 1] - 0; //逆著賦值 } return a; } int compare(bign a, bign b) { //比較兩個bign變量的大小 if (a.len > b.len) return 1; else if (a.len < b.len) return -1; else { for (int i = a.len - 1; i >= 0; i--) { if (a.d[i] > b.d[i]) return
1; else if (a.d[i] < b.d[i]) return -1; } return 0; } } bign add(bign a, bign b) { //高精度加法 bign c; int carry = 0; //進位 for (int i = 0; i < a.len || i < b.len; i++) { int temp = a.d[i] + b.d[i] + carry; c.d[c.len++] = temp % 10; carry
= temp / 10; } if (carry != 0) { c.d[c.len++] = carry; } return c; } bign sub(bign a, bign b) { //高精度減法(使用前需要比較兩個數的大小, 如果被減數小於減數, 需要交換兩個變量,然後輸出負號, 再使用sub函數) bign c; for (int i = 0; i < a.len || i < b.len; i++) { if (a.d[i] < b.d[i]) { a.d[i + 1]--; a.d[i] += 10; } c.d[c.len++] = a.d[i] - b.d[i]; } while (c.len - 1 >= 1 && c.d[c.len - 1] == 0) { c.len--; } return c; } bign multi(bign a, int b) { //高精度與低精度的乘法 bign c; int carry = 0; for (int i = 0; i < a.len; i++) { int temp = a.d[i] * b + carry; c.d[a.len++] = temp % 10; carry = temp / 10; } while (carry != 0) { c.d[c.len++] = carry % 10; carry /= 10; } return c; } bign divide(bign a, int b, int &r) { bign c; c.len = a.len; //被除數的每一位和商的每一位是一一對應的。因此先令長度相等 for (int i = a.len - 1; i >= 0; i--) { r = r * 10 + a.d[i]; if (r < b) c.d[i] = 0; else { c.d[i] = r / b; // r = r % b; //獲得的余數 } } while (c.len - 1 >= 1 && c.d[c.len - 1] == 0) { c.len--; } return c; } bign divide(bign a, int b, int &r) { //高精度除法與低精度除法的運算 // r為余數 bign c; c.len = a.len; for (int i = a.len - 1; i >= 0; i--) { r = r * 10 + a.d[i]; if (r < b) c.d[i] = 0; else { c.d[i] = r / b; r = r % b; } } while (c.len - 1 >= 1 && c.d[c.len - 1] == 0) { c.len--; } return c; } int main() { char str1[1000], str2[1000]; scanf("%s%s", str1, str2); bign a = change(str1); bign b = change(str2); bign c = add(a, b); for (int i = c.len - 1; i >= 0; --i) { printf("%d", c.d[i]); } return 0; }

大整數運算練習