@Guneesh: I don't think your code is correct. You want val to take on the values n, n^2, n^4, n^8, ..., whereas in your code, val takes on the values 1,n, n^2, n^3, .... The algorithm should be more like this: int power() { int ans=1,val=n; while(k) { if(k&1)ans=ans*val; k=k>>1; if(k)val=val*val; } return ans; } Dave
On Saturday, January 19, 2013 5:06:25 AM UTC-6, Guneesh wrote: > consider code to find n^k where n is an integer > > int power() > { > int ans=1,val=1; > while(k) > { > val=val*n; > if(k&1)ans=ans*val; > k=k>>1; > } > return ans; > } > > now if n is is a matrix all you have to do is replace * by matrix > multiplication algorithm > --