LightOJ 1214 Large Division(大整数取模)

来源:互联网 发布:比较好的php框架 编辑:程序博客网 时间:2024/05/21 10:48

题目链接:
LightOJ 1214 Large Division
题意:
大整数取模。输入a,b(-10^200 <= a <= 10^200, b != 0, b是int),判断a能否整除b。
分析:
把大整数写成“从左向右”的形式:如:1234 = ((1 * 10 + 2) * 10 + 3) * 10 + 4.然后根据(n + m) % p = ((n % p) + (m % p)) % p,每步去模。

#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <climits>#include <cmath>#include <ctime>#include <cassert>#define IOS ios_base::sync_with_stdio(0); cin.tie(0);using namespace std;typedef long long ll;const int MAX_N = 250;int T, cases = 0, p;char s[MAX_N];int main(){    scanf("%d", &T);    while(T--){        scanf("%s%d", &s, &p);        printf("Case %d: ", ++cases);        int len = strlen(s);        if(s[0] == '0' && len == 1){        printf("divisible\n");        continue;        }        if(p < 0) p = -p;        int ans = 0, st = 0;        if(s[0] == '-') st = 1;        for(int i = st; i < len; i++){        ans = (int)(((ll) ans * 10 + s[i] - '0') % p);        }        if(ans == 0) printf("divisible\n");        else printf("not divisible\n");    }    return 0;}
0 0