-
Notifications
You must be signed in to change notification settings - Fork 3
/
question33.c
87 lines (64 loc) · 1.07 KB
/
question33.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <stdlib.h>
void display(int f[2][2]){
int i,j;
printf("-------------------\n");
for(i=0;i<2;i++){
for(j=0;j<2;j++){
printf("%d ", f[i][j]);
}
printf("\n");
}
printf("----------------\n");
}
void mul(int a[2][2], int b[2][2]){
int p = a[0][0]*b[0][0] + a[0][1]*b[1][0];
int q = a[0][0]*b[0][1] + a[0][1]*b[1][1];
int r = a[1][0]*b[0][0] + a[1][1]*b[1][0];
int s = a[1][0]*b[0][1] + a[1][1]*b[1][1];
a[0][0] = p;
a[0][1] = q;
a[1][0] = r;
a[1][1] = s;
}
void ipow(int f[2][2], int power){
if(power <= 1){
return;
}
int base[2][2] = {
{1,1},
{1,0}
};
mul(f,f);
ipow(f,power/2);
if(power%2 != 0){
mul(f,base);
}
}
void ipowIterative(int f[2][2],int power){
int base[2][2] = {
{1,1},
{1,0}
};
while(power > 1){
mul(f,f);
if(power%2 !=0){
mul(f,base);
}
power = power/2;
}
}
int fib(int n){
int f[2][2] = {
{1,1},
{1,0}
};
printf("calling pow with power %d\n", n-1);
ipowIterative(f,n-1);
return f[0][0];
}
int main(){
int n = 11;
printf("answer is %d\n", fib(n));
return 0;
}