首页 > 解决方案 > 向量中的 +2 值来自哪里?

问题描述

我试图找到斐波那契数的最后一位。根据作业,我首先生成 Pisano 周期,它是斐波那契数列以 n 为模的重复周期。mod 10 的周期等于 60。我用 C++ 编写了实现 Pisano Period 的代码,但由于某种原因,我最终得到了 62 个值 - 不确定这 2 个值的来源。

n 项之和等于: F(n+2) - 1 ,也在下面的代码中实现:

#include <iostream>
#include <vector>
using namespace std;

vector<uint64_t> fibList; // Fibonacci numbers List
vector<uint64_t> pisanoSequence; // Pisano Sequence list
void generatePisanoSequence(int mod)
{
    fibList.push_back((*(fibList.end()-1) + *(fibList.end()-2)) % mod); // Get the last digits of the next Fibonacci number depending on the modulp. 
    pisanoSequence.push_back(*(fibList.end()-1)); //Put the last digit of the last Fibonacci number in the Pisano Sequence
    if (*(pisanoSequence.end() - 1) == 1 && *(pisanoSequence.end() - 2) == 0) // If we return to having 0 then 1 as inputs to the Pisano sequence that mean we have reached the end of the period of the sequence
    {
        return; // Stop Generating entries
    }
    else
    {
        generatePisanoSequence(mod); // Calculate the next entry.
    }
}
int main()
{
    fibList.push_back(0); // Put 0 to the Fibonacci sequence
    fibList.push_back(1); // Put 1 to the Fibonacci sequence
    pisanoSequence.push_back(0); // Put 0 to the Pisano Sequence
    pisanoSequence.push_back(1); // Put 1 to the Pisano sequence
    generatePisanoSequence(10); // An Examplry Modulos of 1000
    uint64_t n; // Input Fibonacci numbers
    cin >> n;
    n = n % ((pisanoSequence.size()) - 2); //Searching for the right i element // had to delete two of these unwanted elements here
    uint64_t n2 = pisanoSequence[n+2]; //Get the number of F(i)
    n2 = n2 - 1;
    cout << (n2 + 10 ) % 10;
    return 0;
}

标签: c++mathfibonacci

解决方案


推荐阅读