本文主要是介绍寒假第五天--递推递归--Number Sequence,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Number Sequence
Time Limit: 1000MS Memory limit: 65536K
题目描述
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).
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).
输入
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.
输出
For each test case, print the value of f(n) on a single line.
示例输入
1 1 3 1 2 10 0 0 0
示例输出
2 5
提示
知识扩展:本类算法在数字医疗、移动证券、手机彩票、益智类解谜类游戏软件中会经常采用。
来源
f(1 ) = 1 ; f(2) = 1 ; f3 = (A+B); A B 的值不变 ,随着N的增加,如果出现f(n) = 1 ; f(n+1) = 1 ; 那么就找到一个循环节,
示例程序#include <stdio.h>
int a[10000];
int main()
{int i , A , B , n , s;while(scanf("%d %d %d",&A, &B, &n)!=EOF){if(A==0 && B==0 && n==0)break;a[1] = 1 ; a[2] = 1 ; i = 3;while(i < 10000){a[i] = (A*a[i-1]+B*a[i-2])%7 ;if(a[i]==1 && a[i-1]==1)break;i++;}s = i-2 ;if(n <= s)printf("%d\n",a[n]);elseprintf("%d\n", a[ n%s ]);}return 0;
}
#include <stdio.h>
int a[10000];
int main()
{int i , A , B , n , s;while(scanf("%d %d %d",&A, &B, &n)!=EOF){if(A==0 && B==0 && n==0)break;a[1] = 1 ; a[2] = 1 ; i = 3;while(i < 10000){a[i] = (A*a[i-1]+B*a[i-2])%7 ;if(a[i]==1 && a[i-1]==1)break;i++;}s = i-2 ;if(n <= s)printf("%d\n",a[n]);elseprintf("%d\n", a[ n%s ]);}return 0;
}
这篇关于寒假第五天--递推递归--Number Sequence的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!