Approximate test instructions: Enter two nonnegative integers, a, B, and positive integer n. Calculates f (a^b)%n. Among them F[0]=f[1]=1, F[i+2]=f[i+1]+f[i]. That is to calculate the large Fibonacci number and then take the modulus.
First saw the big Fibonacci number, think of the matrix fast power, output wait a few seconds before output, will definitely time out. Because all calculations are to be modulo, set f[i]=f[i] mod n. F[0]=f[1]=1. As soon as the f[i]=f[i+1]=1 appears, the entire sequence repeats. For example n=3, the sequence is 1,1,2,0,2,2,1,0,1,1 ... Items Nineth and tenth are equal to 1, so subsequent sequences will be duplicated.
As to how long it will be repeated, this cannot be directly seen. My program is always judged to know there are two adjacent to 1, so a little risky, but no timeout. Later read the next Rujia book, the book said: Because the remainder of the most n, so the maximum number of N2 will be repeated. This is a conclusion, I do not understand, first remember it.
#include <iostream>#include<cstdio>#include<cstring>#include<cmath>using namespacestd;Const intmaxn=1000000+5; typedef unsignedLong Longull;intMODNUM[MAXN];intMod;intPowermod (ull a,ull B,intc) {ull ans=1; A%=C; while(b) {if(b&1) ans=ans*a%C; A=a*a%C; b=b>>1; } returnans;}intMain () {//freopen ("In.txt", "R", stdin); intT; Ull A, B; scanf ("%d",&t); while(t--) {scanf ("%llu%llu%d",&a,&b,&Mod); if(mod==1|| a==0) {printf ("0\n"); Continue; } modnum[0]=modnum[1]=1; intp=1; for(intI=2;; i++) {Modnum[i]= (modnum[i-1]+modnum[i-2])%Mod; if(modnum[i]==1&& modnum[i-1]==1) {p=i-1; Break; }} printf ("%d\n", Modnum[powermod (a,b,p)-1]); } return 0;}
UVA 11582 Colossal Fibonacci numbers! Grand Fibonacci number