I am trying to find the last digit of Fibonacci numbers. According to the assignment, I generate the Pisano Period first that is the period with which the sequence of Fibonacci numbers taken modulo n repeats. The cycle of mod 10 equals 60. I wrote the code in C++ implementing the Pisano Period, but for some reason I get 62 values in the end - not sure where those 2 values are coming from.
The sum of the n terms equals: F(n+2) - 1 , implemented in the code below as well:
#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;
}