UVA 11582 Colossal Fibonacci numbers! Grand Fibonacci number

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.