Coursera's Algorithmic toolbox assignment solutions( Fibonacci Number Again, Find Product, Last Digit of the Sum of Fibonacci Numbers ) :
Problem 5: Fibonacci Number Again
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
#include <bits/stdc++.h>
using namespace std;
long long unsigned get_p(long long unsigned m) //function to get the pisano period
{
long long unsigned a=0, b=1, c=a+b;
for (long long unsigned int i=0; i<m*m; i++)
{
c=(a+b)%m;
a=b;
b=c;
if(a==0 && b==1)
return i+1;
}
}
int main()
{
long long unsigned n,i,m,p;
cin>>n>>m;
p=get_p(m);
n=n%p;
long long unsigned f[n];
f[0]=0;
f[1]=1;
for(i=2;i<=n;i++)
{
f[i]=(f[i-1]+f[i-2])%m;
}
cout<<f[n]<<endl;
}
In the pdf from coursera resources section where the question of this problem is written you can find there the definition of pisano period or read it on geeksforgeeks (see the example carefully in the link , that's what i have done here in this code) and then you can easily understand this code.
Problem 6: Last Digit of the Sum of Fibonacci Numbers
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long unsigned n,i,sum=1;
cin>>n;
long long unsigned f[n];
f[0]=0;
f[1]=1;
for(i=2;i<=n;i++)
{
f[i]=(f[i-1]+f[i-2])%10;
sum+=f[i];
}
cout<<sum%10;
}
This code is simple. There's no need for any explanation.
Guys , if you have any queries related to a question or need more explanation, comment down below!
Comments
Post a Comment