sicily 1020. Big Integer 大數求模

http://blog.163.com/hong_feiy/blog/static/207325071201282324736756/

回想小學怎麼做除法可以幫助理解大數求模

#include <iostream>
#include <string>
using namespace std;
int div(string x, int b) {
    int r, k;
    for ( k = 0; k < x.length(); k++ )
    {
        r = 10 * r + x.at(k) - '0';  // 大數求摩,好神奇!
        r %= b;  // 因爲高位的數字如果大於b,則該數字num 肯定等於b * n*10 + mo。 而mo就等於r % b
    }
    return r;
}
int main()
{
    int t;
    int n;
    unsigned b[100];
    string x;  // Each VeryLongInteger will be 400 or fewer characters in length,
    // and will only contain digits (no VeryLongInteger will be negative).
    int r[100];
    int m;
    int i, j;
    cin >> t;
    for( i = 0; i < t; i++ ) {
        cin >> n;
        m = 1;
        for( j = 0; j < n; j++) {
            cin >> b[j];
            m*= b[j];
        }
        cin >> x;
        for( j = 0; j < n; j++) {
            r[j] = div(x, b[j]);
        }
        cout << "(";
        for( j = 0; j < n-1; j++) {
            cout << r[j] << ',';
        }
        cout << r[j] << ')' << endl;
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章