标签:
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 3
1 2 10
0 0 0
Sample Output
2
5
#include<stdio.h>
int main(void)
{
int a, b, n;
int f1, f2, f3;
while(1)
{
scanf("%d%d%d", &a, &b, &n);
if(a==0 && b==0 && n==0)
break;
f1 = 1;
f2 = 1;
f3 = 1;
for(int i = 3; i <= n; i++)
{
f3 = (a*f2 + b*f1)%7;
f1 = f2;
f2 = f3;
}
printf("%d\n", f3);
}
return 0;
}
可惜暴力的后果是WA,再仔细看一下数据范围,n的取值达到一亿。由于数据范围很大,因此这题不适合暴力。
那么这道类似斐波那契数列的题目该如何搞呢?很明显,f(n-1)和f(n-2)的取值只可能有0, 1, 2, 3, 4, 5, 6这七种情况。因此f(n-1)+f(n-2)的组合一共有7*7种情况,这说明什么呢?说明数列(以f3作为第一个数)出现循环最多在第50个数(最坏的情况)。
修改后的程序:
#include<stdio.h>
int main(void)
{
int a, b, n;
int f1, f2, f3;
int arr[50]; // 空间够用的情况下多一个数据也没关系啦
int j;
while(1)
{
scanf("%d%d%d", &a, &b, &n);
if(a==0 && b==0 && n==0)
break;
f1 = 1;
f2 = 1;
j = 0;
for(int i = 3; i <= 52; i++)
{
f3 = (a*f2 + b*f1)%7;
f1 = f2;
f2 = f3;
arr[j++] = f3;
}
if(n==1 || n==2)
printf("%d\n", 1);
else
printf("%d\n", arr[(n-3)%49]);
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/xpjiang/p/4410070.html