hdu 1005 求模运算

来源:互联网 发布:青岛seo建站 编辑:程序博客网 时间:2024/05/17 01:21

Number Sequence


Problem Description
A number sequence is defined as follows:

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

Given A, B, and n, you are to calculate the value of f(n).
 

Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
 

Output
For each test case, print the value of f(n) on a single line.
 

Sample Input
1 1 31 2 100 0 0
 

Sample Output
25
Author
CHEN, Shunbao
Source
ZJCPC2004

Recommend
JGShining   |   We have carefully selected several similar problems for you:  1008 1021 1019 1009 1012 

题意概括:这是一个数列的运算问题,我刚开始的时候感觉把公式套一下就好了,然后发现n的区间是[1,100000000],所以一定会出现内存超限或者时间超限的问题。然后我就翻看了一下大佬的博客。对于这种求模的问题多是有规律的东西,肯定能找到循环的位置。然后我就按自己的想法写的代码。当f[i]=1并且f[i-1]=1时,肯定就到了循环的位置,找到循环节,然后就对n进行求余就可以使用很少的时间求解了。

//from:hdu 1005//time:2017.10.13#include <stdio.h>#include <string.h>int main(){int a,b,n;int i,f[1000];f[1]=f[2]=1;while(1){scanf("%d%d%d",&a,&b,&n);if(a==0&&b==0&&n==0)break;if(n==1||n==2)printf("1\n");else{for(i=3;i<110;i++){f[i]=(a*f[i-1]+b*f[i-2])%7;if(f[i]==1&&f[i-1]==1)//同时为1的时候就与题目中f[1]==1&&f[2]==1构成循环了 break;}f[0]=f[i-2];//这里对于刚好达到一个循环的时候下标就为0了 n%=i-2;printf("%d\n",f[n]);}}return 0;}


原创粉丝点击