Raising a 2D array to a power in C -
i'm using c , have 2d array representing square matrix. want calculate matrix power of n
, given integer.
i'm after efficient way this. first thought multiply matrix n
times heard of exponentiation squaring. i'm not sure how implement this, please guide me through it?
here basic outline:
matrix matrixexponent(matrix m, int n) { matrix accumulator = matrixidentity(); matrix power2 = m; while(n != 0) { if(n & 1) accumulator = matrixmultiply(&accumulator, &power2); power2 = matrixmultiply(&power2, &power2); n = n / 2; } return accumulator; }
you store accumulator, partially computed exponent. given integer exponent can broken down series of power-of-2 exponents multiplied together. example when raising array power of 14 (1110 in binary), matrix multiplied 14 times equal to:
m14 = m8 * m4 * m2
so compute powers of 2 repeatedly multiplying power2 itself, while stepping through each bit of integer exponent n, , multiplying power2 accumulator each time bit 1.
Comments
Post a Comment