码迷,mamicode.com
首页 > 其他好文 > 详细

Raising Modulo Numbers 取模+快速幂

时间:2016-08-06 23:15:56      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

Raising Modulo Numbers
题目地址:http://poj.org/problem?id=1995

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 AiBifrom 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

3
16
4
2 3
3 4
4 5
5 6
36123
1
2374859 3029382
17
1
3 18132

Sample Output

2
13195
13

题意:首先输入z组测试数据,然后输入俩整数,隔行分开,前者为M,后者代表接下来输入H行数据,每行俩整数a、b,求所有a的b次方相加后对M取模

   思路:1:a的b次方采用快速幂

            2:(a+b)%mod = (a%mod + b%mod)%mod

代码如下:

 1 #include<cstdio>
 2 __int64 fun(int n, int m, int mod)
 3 {
 4     __int64 ans=1,base=n;
 5     while(m)
 6     {
 7         if( m&1 )/*为奇数时为真 */    ans=(base*ans)%mod;
 8         base=(base*base)%mod;
 9         m>>=1;//相当于 m=m/2 
10     }
11     return ans;
12 }
13 int main()
14 {
15     int t;
16     scanf("%d",&t);
17     while( t-- )
18     {
19         __int64 M, H, a, b, i, j, k, mod=0;
20         scanf("%I64d %I64d",&M, &H);
21         for(i=0; i<H; i++)
22         {
23             scanf("%I64d %I64d", &a, &b);
24             k = fun(a, b, M);
25             mod = (mod%M + k) % M;//k已经提前对M取余 
26         }
27         printf("%I64d\n",mod);
28     }
29     return 0;
30 }

 

Raising Modulo Numbers 取模+快速幂

标签:

原文地址:http://www.cnblogs.com/123tang/p/5744950.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!