http://poj.org/problem?id=1995
The problem is to analyze the fast power-taking mode.
A^b%c (This is the famous RSA public key encryption method), when a is large, the direct solution to this problem is not likely
Using the formula a*b%c= ((a%c) *b)%c
This processing is done at every step, which solves the problem that a^b may be too large, but the time complexity of the algorithm is still not optimized
This can be optimized with a fast power algorithm:
Http://www.cnblogs.com/qlky/p/5020402.html
And then combine the modulus formula:
(A + b)% P = (a% p + b% p)% p
Http://www.cnblogs.com/qlky/p/5020632.html
1#include <iostream>2#include <cstdlib>3#include <cstdio>4#include <cmath>5#include <algorithm>6 7 using namespacestd;8 9 Long LongMoDLong LongALong LongBLong Longm)Ten { One Long LongR =1,Base=A; A while(b!=0) - { - if(b&1) theR= r*Base%m; - Base=Base*Base%m; -b>>=1; - } + returnR; - } + A intMain () at { - Long Longt,n,m,i; - Long Longsum =0; -scanf"%lld",&t); - while(t--) - { inscanf"%lld%lld",&m,&n); - to Long Longb; +scanf"%lld%lld",&a,&b); -sum =mod (a,b,m); the * for(i =0; i<n-1; i++) $ {Panax Notoginsengscanf"%lld%lld",&a,&b); -sum+=mod (a,b,m); thesum%=m; + } Aprintf"%lld\n", sum); the + } - return 0; $}
Fast Power Modulo (POJ 1995)