HDU-1005(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
题目大意:每个样例输入a,b,n三个数字
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
要求输出f(n);
很明显题目意思明确看起来很好解,但是却有时间和内存限制!
当然不死心的的我还是尝试了硬解,不出意外内存超限了
这个题目其实有多种方式求解
比较主流的是规律法求解

AC代码

这个f(n-1)和f(n-2)都是小于7的两个数字的组合周期为7*7=49
这是使用向量的方式

#include<cstdio>
#include<vector>
using namespace std;
int main()
{
    int a,b,n;
    vector<int> s;
    while(~scanf("%d %d %d",&a,&b,&n))
    {
        if(a==0&&b==0&&n==0)
            break;
        n=n%49;
        s.push_back(1);
        s.push_back(1);
        for(int i=2; i<n; i++)
            s.push_back((a*s[i-1]+b*s[i-2])%7);
        printf("%d\n",s[n-1]);
        while(!s.empty())
            s.pop_back();
    }
    return 0;
}

还有用递归的方式

#include<cstdio>
using namespace std;
int f(int a,int b,int n)
{
    if(n==1||n==2)
        return 1;
    return (a*f(a,b,n-1)+b*f(a,b,n-2))%7;
}
int main()
{
    int a,b,n;
    while(~scanf("%d %d %d",&a,&b,&n))
    {
        if(a==0&&b==0&&n==0)
            break;
        n=n%49;
        printf("%d\n",f(a,b,n));
    }
    return 0;
}

当然如果一时之间看不出也没关系;
我们知道它肯定是有规律的我们的起点是两个1(第一个和第二个数字是1)那么再次找到两个1的时候就打印了一个周期了
我这里的数组定义了1000是尽量大的,其实50就可以了

#include<stdio.h>
using namespace std;
int s[1000];
int main()
{
    int a,b,n;
    s[1]=1;
    s[2]=1;
    while(~scanf("%d %d %d",&a,&b,&n))
    {
        if(a==0&&b==0&&n==0)
            break;
        int i;
        for(i=3; i<100; i++)
        {
            s[i]=(a*s[i-1]+b*s[i-2])%7;
            if(s[i]==1&&s[i-1]==1)//当找到两个连续1时走完一个周期周期为i-2
                break;
        }
        s[0]=s[i-2];
        n=n%(i-2);
        printf("%d\n",s[n]);
    }
    return 0;
}

当然还有其他的解法,比如建立二维向量用矩阵求

猜你喜欢

转载自blog.csdn.net/qq_43984169/article/details/87463431