forked from r0drigopaes/paa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfib_squaring.cpp
74 lines (58 loc) · 1.08 KB
/
fib_squaring.cpp
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
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
typedef lli M[2][2];
M m = {{1,1},{1,0}};
void multi_matrix(M a, M b, M c)
{
c[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0];
c[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1];
c[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0];
c[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1];
}
void assign(M a, M b)
{
a[0][0] = b[0][0];
a[0][1] = b[0][1];
a[1][0] = b[1][0];
a[1][1] = b[1][1];
}
/*
n >=1
*/
void powering(M a, M result, int n)
{
if (n==1)
{
assign(result, a);
return;
}
M half;
if (n%2==0)
{
powering(a, half, n/2);
multi_matrix( half, half, result);
return;
}
else
{
M temp;
powering(a, half, (n-1)/2 );
multi_matrix( half, half, temp);
multi_matrix( temp, a, result);
return;
}
}
long long int fib(int n)
{
M result;
powering(m, result, n);
return result[0][1];
}
int main()
{
int n;
scanf("%d",&n);
printf("%lld\n", fib(n));
return 0;
}