zoukankan      html  css  js  c++  java
  • Number Sequence

    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
     

    仔细看一下数据范围,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<cstdio>
    int main()
    {
        int a,b,n;
        while(scanf("%d%d%d",&a,&b,&n)!=EOF)
        {
            int ans[55]={0};
            int f1,f2,i;
            if(a==0&&b==0&&n==0)
                break;
            f1=f2=1;
            for(i=0;;i++)
            {
                ans[i]=(a*f2+b*f1)%7;
                f1=f2;
                f2=ans[i];
                if(i>=3&&ans[i-1]==ans[0]&&ans[i]==ans[1])
                    break;
            }
            if(n==1||n==2)
                printf("1
    ");
            else
                printf("%d
    ",ans[(n-3)%(i-1)]);
        }
        return 0;
    }
  • 相关阅读:
    Windows照片查看器全屏浏览查看
    Windows调出软键盘
    IE叉事件
    对gridview的小改动
    gridview小把戏
    安全认证(转)
    用数组的方式实现DataTable中的distinct(转)
    TreeView的简单应用
    禁止按钮重复提交
    配置Microsoft Visual SourceSafe 2005的Internet访问(转)
  • 原文地址:https://www.cnblogs.com/coder-tcm/p/8987348.html
Copyright © 2011-2022 走看看