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:
Sample Input:
1 1 3
1 2 10
0 0 0
Sample Output:
2
5
解题思路:
刚看到这道题的时候,就没多想,直接写了个斐波那契数列求余的简单代码,然后果断内存超出了。。。
后来仔细想了想,看到这个对7求余的式子,会不会有什么规律? 我把斐波那契数列的前50项都算了出来,再代入题目中的式子,发现这些余数始终在 {0,1,2,3,4,5,6} 这7个数中间出现,所以这个式子的结果只可能有7×7=49种可能,也就是说数组开到 f[50] 就完全足够了,最终的结果的那一项对49求余即可f[n%49] !!!具体的我们看代码吧↓↓↓
程序代码:
C/C++版本:
#include<stdio.h> #include<string.h> #include<stdlib.h> int f[50]; int main() { int a,b,i,n; while(~scanf("%d %d %d",&a,&b,&n)) { if(!a&&!b&&!n) break; f[1]=f[2]=1; for(i=3;i<=49;i++) f[i]=(a*f[i-1]+b*f[i-2])%7; printf("%d\n",f[n%49]); } return 0; }
Java版本:
import java.util.*; public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int [] f=new int[50]; while(input.hasNext()) { int a=input.nextInt(); int b=input.nextInt(); int n=input.nextInt(); if(a==0&&b==0&&n==0) System.exit(0); f[1]=f[2]=1; for(int i=3;i<=49;i++) f[i]=(a*f[i-1]+b*f[i-2])%7; System.out.println(f[n%49]); } input.close(); } }