POJ1995 Raising Modulo Numbers

来源:互联网 发布:小米手环数据修改攻略 编辑:程序博客网 时间:2024/04/25 13:37
Time Limit:1000MS     Memory Limit:30000KB     64bit IO Format:%lld & %llu
Submit Status

Description

People are different. Some secretly read magazines full of interesting girls' pictures, others create an A-bomb in their cellar, others like using Windows, and some like difficult mathematical games. Latest marketing research shows, that this market segment was so far underestimated and that there is lack of such games. This kind of game was thus included into the KOKODáKH. The rules follow: 

Each player chooses two numbers Ai and Bi and writes them on a slip of paper. Others cannot see the numbers. In a given moment all players show their numbers to the others. The goal is to determine the sum of all expressions Ai Bi from all players including oneself and determine the remainder after division by a given number M. The winner is the one who first determines the correct result. According to the players' experience it is possible to increase the difficulty by choosing higher numbers. 

You should write a program that calculates the result and is able to find out who won the game. 

Input

The input consists of Z assignments. The number of them is given by the single positive integer Z appearing on the first line of input. Then the assignements follow. Each assignement begins with line containing an integer M (1 <= M <= 45000). The sum will be divided by this number. Next line contains number of players H (1 <= H <= 45000). Next exactly H lines follow. On each line, there are exactly two numbers Ai and Bi separated by space. Both numbers cannot be equal zero at the same time.

Output

For each assingnement there is the only one line of output. On this line, there is a number, the result of expression 

(A1B1+A2B2+ ... +AHBH)mod M.

Sample Input

31642 33 44 55 63612312374859 30293821713 18132

Sample Output

213195

13

原理:
模运算与基本四则运算有些相似,但是除法例外。其规则如下:(a + b) % p = (a % p + b % p) % p(a – b) % p = (a % p – b % p) % p (2)(a * b) % p = (a % p * b % p) % p (3)(a^b) % p = ((a % p)^b) % p (4)结合律:((a+b) % p + c) % p = (a + (b+c) % p) % p (5)((a*b) % p * c)% p = (a * (b*c) % 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)
<pre name="code" class="cpp">#include<cstdio>__int64 qpow(__int64 x,__int64 y,__int64 z){__int64 base=x,ans=1;while(y){if(y&1){ans=ans*base%z;}base=base*base%z;y>>=1;}return ans%z;}int main(){__int64 t,n,mod,sum;scanf("%I64d",&t);while(t--){sum=0;scanf("%I64d",&mod);scanf("%I64d",&n);while(n--){__int64 a,b;scanf("%I64d %I64d",&a,&b);sum+=qpow(a,b,mod);}printf("%I64d\n",sum%mod);} return 0;}


0 0
原创粉丝点击