递归:Pell数列C++实现

描述

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 < 30),代表Pell数列的第k项。

输出

n行,每行输出Pell数列的第k项模上32767的值。

样例输入

2
1
8

样例输出

1
408

代码

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

using namespace std;

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


int Pell(int n)
{
          
   
    int c = 1;
    int b = 2;
    int a;

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

    for(int i=3; i<=n; i++)
    {
          
   
        a= (2*b + c) % mod_num;
        c = b;
        b = a;
    }
    return a;
}

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 << Pell(k) << endl;
    }

    return 0;
}
经验分享 程序员 微信小程序 职场和发展