大数之取摸问题

来源:互联网 发布:天刀萝莉少女捏脸数据 编辑:程序博客网 时间:2024/05/26 23:00

杭电1212Big Number


大数取摸问题;


Problem Description
As we know, Big Number is always troublesome. But it's really important in our ACM. And today, your task is to write a program to calculate A mod B.
To make the problem easier, I promise that B will be smaller than 100000.
Is it too hard? No, I work it out in 10 minutes, and my program contains less than 25 lines.
Input
The input contains several test cases. Each test case consists of two positive integers A and B. The length of A will not exceed 1000, and B will be smaller than 100000. Process to the end of file.
Output
For each test case, you have to ouput the result of A mod B.
Sample Input
2 3
12 7
152455856554521 3250
Sample Output
2
5
1521


之前看了好多取摸的知识点,当看到这题大数取摸时,感觉好蒙的,(原来知识点是知识点只有被虐以后才会慢慢的用);正如这题一样。这里面不仅仅只是取摸的运算,还用到了递推,根据递推推出大数取摸的模板公式。


我们先看看递推是怎么推出模板的吧。
先看两位数的,12%9;===(1*10%9+2)%9;
再看三位数的,123%9 ==={((1*10%9+2)%9)*10+3}%9;
四位也就同理了啊;1234%9==(在三位的基础上*10+4)%9;

五位6位都是这样的是不是找到规律了。


可以打出模板了吧、
sum = 0;
        for(i = 0; i < k; i++){
            sum = sum*10+a[i]-'0';
            sum = sum%b;

        }


模板出来了,ac就不再话下了啊,看代码,很短,是不是吓到了。这就是算法的威力所在啊,


#include<stdio.h>
#include<string.h>
int main()
{
    char a[1001];
    int b, sum, k, i;
    while(scanf("%s %d",a, &b) != EOF){
        k = strlen(a);
        sum = 0;
        for(i = 0; i < k; i++){
            sum = sum*10+a[i]-'0';
            sum = sum%b;
        }
        printf("%d\n",sum);
    }
    return 0 ;
}

0 0
原创粉丝点击