/*
It takes a while before it is noticeable. In fact, the series is just 60 numbers long and then it repeats the same sequence again and again all the way through the Fibonacci series – for ever. The series of final digits repeats with a cycle length of 60 (Refer this for explanations of this result).
So, instead of calculating the Fibonacci number again and again, pre-compute the units digit of first 60 Fibonacci number and store it in an array and use that array values for further calculations.
Link: Program to find last digit of n’th Fibonnaci Number
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define sf scanf
#define pf printf
LL f[65] = {0};
LL fib(LL n)
{
f[0] = 0;
f[1] = 1;
for (LL i = 2; i <= n; i++)
{
f[i] = (f[i-1] + f[i-2])%10;
}
return f[n];
}
LL findLastDigit(LL n)
{
fib(60);
return f[n%60];
}
int main()
{
int t , tc=0;
LL n;
sf("%d", &t);
while(t--)
{
memset(f , 0 , sizeof f);
sf("%lld", &n);
pf("Case %d: %lld is the last digit.\n", ++tc, findLastDigit(n));
}
return 0;
}
It takes a while before it is noticeable. In fact, the series is just 60 numbers long and then it repeats the same sequence again and again all the way through the Fibonacci series – for ever. The series of final digits repeats with a cycle length of 60 (Refer this for explanations of this result).
So, instead of calculating the Fibonacci number again and again, pre-compute the units digit of first 60 Fibonacci number and store it in an array and use that array values for further calculations.
Link: Program to find last digit of n’th Fibonnaci Number
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define sf scanf
#define pf printf
LL f[65] = {0};
LL fib(LL n)
{
f[0] = 0;
f[1] = 1;
for (LL i = 2; i <= n; i++)
{
f[i] = (f[i-1] + f[i-2])%10;
}
return f[n];
}
LL findLastDigit(LL n)
{
fib(60);
return f[n%60];
}
int main()
{
int t , tc=0;
LL n;
sf("%d", &t);
while(t--)
{
memset(f , 0 , sizeof f);
sf("%lld", &n);
pf("Case %d: %lld is the last digit.\n", ++tc, findLastDigit(n));
}
return 0;
}
