#include<stdio.h>
#define MOD 100000009
#define REP(i, n) for(i = 0; i < n; ++i)
void mul(int a[2][2],int b[2][2])
{
int i,j,k;
int c[2][2];
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=0;
for(k=0;k<2;k++)
{
c[i][j]+=(a[i][k]*b[k][j]);
}
}
} // matrix multiply
i=0;j=0;
REP(i,2)
REP(j,2)
b[i][j]=c[i][j]; // copying the value in back to b[][]
return;
}
void calc(int a[2][2],int b[2][2],int p)
{
int i,j,k;
if(p==1)
{
REP(i,2)
REP(j,2)
b[i][j]=a[i][j];
return;
}
if(p%2==0)
{
calc(a,b,p/2);
mul(b,b);
}
else
{
calc(a,b,p/2);
mul(b,b);
mul(b,a);
}
return;
}
int main()
{
int t[2][2]={
{0,1},
{1,1}
};
int f[2][1]={
{1},
{1}
};
int n=3;
int i,j;
int b[2][2];
calc(t,b,n-1);
REP(i,2)
REP(j,2)
printf("%d ",b[i][j]);
/* int g[2][1]={
{b[0][0]*f[0][0]+b[0][1]*f[1][0]},
{b[1][0]*f[0][0]+b[1][1]*f[1][0]}
};
*/
getch();
return 0;
}
this is a code for finding nth fibo number in logn time. I have multiplied a matrix T n-1 times. But the problem with code is that it is same output for n=3 and n=4 both. I am not able to figure out the error. thanks if you can help me in this.
Answer for n=3 and n=4 which it is giving: 1 1 1 2 which is wrong. So can you figure out where can be the problem ? And it is also giving wrong output some other cases also. I think there is some logical problem.thanks in advance.