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.c++
To make the problem easier, I promise that B will be smaller than 100000.web
Is it too hard? No, I work it out in 10 minutes, and my program contains less than 25 lines.promise
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.app
Output
For each test case, you have to ouput the result of A mod B.less
Sample Inputsvg
2 3 12 7 152455856554521 3250
Sample Outputspa
2 5 1521
题意
用第一个数mod第二个数,输出结果。code
题解
既然这样出题了,那么确定明眼人都能想到的办法是行不通的,这时候咱们就要用到费马小定理。xml
费马小定理可以帮助咱们快速求一个高次幂的模。blog
在作题以前,先了解这样一些结论:
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;
固然还有ab mod c=(a mod c+b mod c)mod c;
如35 mod 3=((5%3)*(7%3))%3
直接贴代码了,代码不长,直接看就能看懂。
#include<bits/stdc++.h> 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)