CCF NOI1071. Pell数列 (C++)

版权声明:代码属于原创,转载请联系作者并注明出处。 https://blog.csdn.net/weixin_43379056/article/details/84998202

1071. Pell数列

题目描述

Pell数列a1,a2,a3…的定义是这样的:a1=1, a2=2, … ,an = 2*an-1 + an-2 (n>2)。给出一个正整数k,要求Pell数列的第k项模上32767是多少。

输入

第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数k (1<=k<1000000)。

输出

n行,每行输出对应一个输入。输出应是一个非负整数。

样例输入

2
1
8

样例输出

1
408

数据范围限制

1<=n<=10,1<=k<1000000

C++代码

#include <iostream>
#include <assert.h>
#include <ctime>

using namespace std;

const int mod_num = 32767;
const int max_k   = 1000000;

// PellSeq is non-recursive
int PellSeq(int n)
{
    int PellSn_2 = 1; // Pell Sequence a1 = 1
    int PellSn_1 = 2; // Pell Sequence a2 = 2
    int PellSn;       // Pell Sequence an = ?

    if (n <= 2)
    {
        return n;
    }

    for(int i=3; i<=n; i++)
    {
        PellSn   = (2*PellSn_1 + PellSn_2) % mod_num;
        PellSn_2 = PellSn_1;
        PellSn_1 = PellSn;
    }
    return PellSn;
}

int main()
{
    int n;

    cin >> n;

    assert(n>=1 && n<=10);

    int k;

    for (int i=1; i<=n; i++)
    {
        cin >> k;

        assert(k>=1 && k<max_k);

        cout << PellSeq(k) << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43379056/article/details/84998202