poj 1995 快速幂的应用

来源:互联网 发布:js 新建 jsonarray 编辑:程序博客网 时间:2024/06/06 15:58
Raising Modulo Numbers
Time Limit: 1000MS Memory Limit: 30000KTotal Submissions: 8821 Accepted: 5351

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

21319513

Source

CTU Open 1999


快速幂的使用始于一个公式 (a*b)%m =(a%m)*(b%m)%m
当 a==b 时 公式就是(a^2)%m
而当幂很大时,比如a^n%m就可以等于((a^2%m)^n/2)%m可以带入几个数据验证一下。
通过不断降幂最后可以使得n/2等于1,这时就可以直接得到余数了
不过这样的处理是对于n为偶数的时候,而当n为奇数时,需要先提取出一个数,这时候就让奇数变成了偶数,最后让底数*上一次得到的余数再对该数求余

#include<iostream>using namespace std;long long f(long long a,long long b ,long long c){long long ans = 1;while(b){if(b&1)ans = (a*ans) %c;b = b>>1;a = (a*a)%c;}return ans;}int main(){long long N;cin>>N;while(N--){int M;cin>>M;long long H,A[45000],B[45000],c[45000],sum = 0;cin>>H;for(int i = 0 ; i < H ; i ++){cin>>A[i]>>B[i];c[i] = f(A[i],B[i],M);sum += c[i] ;}sum %= M;cout<<sum<<endl;}}

原创粉丝点击