help with divide & conquer problem
Posted: Sun May 14, 2006 9:15 pm
Hi ! I am having troubles in doing an implementation of a very common problem.
I have a matrix A and I want to get the matrix A^n. As far as I know the best way to do this is to make something like:
A^(n/2)*A^(n/2) if n mod 2==0
A^(n-1)*A if n mod 2 !=0
I get the idea of the recursive algorithm, but I don't know how to make an implementation of this, where to save the temporary results and some other little things that appears when I am trying to coding.
I get from the web this example:
^n
| 0 1 | = | fn-2 fn-1 |
| 1 1 | = | fn-1 fn |
means that the matrix [0 1]^n is equal to the matrix where fn = the
nth fibonacci number : [1 1]
I don't understand why this code make the implementation to get the nth fibonacci using the method explained above
Divide_Conquer_Fib(n) {
i = h = 1;
j = k = 0;
while (n > 0) {
if (n%2 == 1) { // if n is odd
t = j*h;
j = i*h + j*k + t;
i = i*k + t;
}
t = h*h;
h = 2*k*h + t;
k = k*k + t;
n = (int) n/2;
}
return j;
}
well, if someone can help me, I would appreciate very much
thanks!
bye
I have a matrix A and I want to get the matrix A^n. As far as I know the best way to do this is to make something like:
A^(n/2)*A^(n/2) if n mod 2==0
A^(n-1)*A if n mod 2 !=0
I get the idea of the recursive algorithm, but I don't know how to make an implementation of this, where to save the temporary results and some other little things that appears when I am trying to coding.
I get from the web this example:
^n
| 0 1 | = | fn-2 fn-1 |
| 1 1 | = | fn-1 fn |
means that the matrix [0 1]^n is equal to the matrix where fn = the
nth fibonacci number : [1 1]
I don't understand why this code make the implementation to get the nth fibonacci using the method explained above
Divide_Conquer_Fib(n) {
i = h = 1;
j = k = 0;
while (n > 0) {
if (n%2 == 1) { // if n is odd
t = j*h;
j = i*h + j*k + t;
i = i*k + t;
}
t = h*h;
h = 2*k*h + t;
k = k*k + t;
n = (int) n/2;
}
return j;
}
well, if someone can help me, I would appreciate very much
thanks!
bye