寒假第五天--递推递归--Number Sequence

来源:互联网 发布:matlab混合编程设置 编辑:程序博客网 时间:2024/05/22 07:59

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).

输入

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 31 2 100 0 0

示例输出

25

提示

知识扩展:本类算法在数字医疗、移动证券、手机彩票、益智类解谜类游戏软件中会经常采用。

来源

 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]);        else            printf("%d\n", a[ n%s ]);    }    return 0;}

0 0
原创粉丝点击