1. 程式人生 > >Number Sequence 【杭電-1005】 附題+詳解

Number Sequence 【杭電-1005】 附題+詳解

/*Number Sequence
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 102803    Accepted Submission(s): 24875


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>
#include<string.h>
int fun(int a,int b,int n){
 if(n==1)           return 1;
 else if(n==2)      return 1;
 else               return (a*fun(a,b,n-1)+b*fun(a,b,n-2))%7;
}
int main()
{
    int a,b,n;
 while(~scanf("%d %d %d",&a,&b,&n),a+b+n){
  printf("%d\n",fun(a,b,n%49));   //n是以49為週期的函式直接取餘,否則超時
 }
 return 0;
}
中文題目: 序列數
中文翻譯-題目大意: f(n)函式滿足f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7;其中A,B,n的值是隨機輸入的,
                    當A,B,n都為0時,程式結束。
解題思路:很明顯,本題可以運用到遞迴思想,當然,也可以構造一個關於n的f(n)的函式關係。
難點詳解:本題的難點在於很容易超時,只有我們發現一個規律:n是以49為週期的;即我們可以對n取餘49,以減少執行步驟,縮短時間。
關鍵詞:  遞迴  取餘
解題人:   楊聖潔
解題時間:2014.8.1
解題體會:有時候,不是想到這道題的解法就能解出來,更多時候,一個接一個的規律,或者說陷阱,我需要的是一種更深層次的對問題的思考!