O(lgn) version by matrix product