Big Number( 杭电ACM省赛集训队选拔赛之热身赛)

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

题意
用第一个数mod第二个数,输出结果。

题解
既然这样出题了,那么肯定明眼人都能想到的办法是行不通的,这时候我们就要用到费马小定理。

费马小定理能够帮助我们快速求一个高次幂的模。

在做题之前,先了解这样一些结论:

AB % C = (A%C * B%C)%C
(A+B)%C = (A%C + B%C)%C
如 532 mod 7 =(500%7+30%7+2%7)%7;
当然还有a
b mod c=(a mod c+b mod c)mod c;
如35 mod 3=((5%3)*(7%3))%3

直接贴代码了,代码不长,直接看就能看懂。
Big Number( 杭电ACM省赛集训队选拔赛之热身赛)_第1张图片

#include
using namespace std;
typedef long long ll;

int main()
{
    char arr[1005];
    ll b;
    while(scanf("%s",arr) != EOF)
    {
        scanf("%lld",&b);
        int r=0;
        int len = strlen(arr);
        for(int i=0;i<len;i++)
            r = (r*10+((arr[i]-'0')%b))%b;
        printf("%lld\n",r);
    }
    // system("pause");
    return 0;
}

模运算补充知识

运算规则
模运算与基本四则运算有些相似,但是除法例外。其规则如下:   

(a + b) % p = (a % p + b % p) % p (1)   //用到了这个

(a - b) % p = (a % p - b % p) % p (2)   

(a * b) % p = (a % p * b % p) % p (3)   

ab % p = ((a % p)b) % p (4)   

结合率:

((a+b) % p + c) % p = (a + (b+c) % p) % p (5)

((ab) % p * c)% p = (a * (bc) % p) % p (6)

交换率: (a + b) % p = (b+a) % p (7)

(a * b) % p = (b * a) % p (8)   

分配率: ((a +b)% p * c) % p = ((a * c) % p + (b * c) % p) % p (9)

重要定理

若a≡b (% p),则对于任意的c,都有(a + c) ≡ (b + c) (%p);(10)   

若a≡b (% p),则对于任意的c,都有(a * c) ≡ (b * c) (%p);(11)   

若a≡b (% p),c≡d (% p),则 (a + c) ≡ (b + d) (%p),(a - c) ≡ (b - d) (%p),   (a * c) ≡ (b * d) (%p),(a / c) ≡ (b / d) (%p); (12)   

若a≡b (% p),则对于任意的c,都有ac≡ bc (%p); (13)

你可能感兴趣的:(ACM)