-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMatrix Exponentiation
More file actions
90 lines (73 loc) · 1.72 KB
/
Matrix Exponentiation
File metadata and controls
90 lines (73 loc) · 1.72 KB
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
86
87
88
// JAVA program to find value of f(n) where
// f(n) is defined as
// F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3
// Base Cases :
// F(0) = 0, F(1) = 1, F(2) = 1
import java.io.*;
class GFG {
// A utility function to multiply two
// matrices a[][] and b[][].
// Multiplication result is
// stored back in b[][]
static void multiply(int a[][], int b[][])
{
// Creating an auxiliary matrix to
// store elements of the
// multiplication matrix
int mul[][] = new int[3][3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
mul[i][j] = 0;
for (int k = 0; k < 3; k++)
mul[i][j] += a[i][k]
* b[k][j];
}
}
// storing the multiplication
// result in a[][]
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
// Updating our matrix
a[i][j] = mul[i][j];
}
// Function to compute F raise to
// power n-2.
static int power(int F[][], int n)
{
int M[][] = {{1, 1, 1}, {1, 0, 0},
{0, 1, 0}};
// Multiply it with initial values
// i.e with F(0) = 0, F(1) = 1,
// F(2) = 1
if (n == 1)
return F[0][0] + F[0][1];
power(F, n / 2);
multiply(F, F);
if (n%2 != 0)
multiply(F, M);
// Multiply it with initial values
// i.e with F(0) = 0, F(1) = 1,
// F(2) = 1
return F[0][0] + F[0][1] ;
}
// Return n'th term of a series defined
// using below recurrence relation.
// f(n) is defined as
// f(n) = f(n-1) + f(n-2) + f(n-3), n>=3
// Base Cases :
// f(0) = 0, f(1) = 1, f(2) = 1
static int findNthTerm(int n)
{
int F[][] = {{1, 1, 1}, {1, 0, 0},
{0, 1, 0}} ;
return power(F, n-2);
}
// Driver code
public static void main (String[] args) {
int n = 5;
System.out.println("F(5) is "
+ findNthTerm(n));
}
}