Finding the largest $3^k$ number less than the natural number

42 Views Asked by At

Given the natural number $N$ in binary representation (computer memory). How to obtain the representation of the $N\rightarrow\sum^{M}_{k=0}(a_k\cdot(3^k+1))$ form or, at least, how to find the $M$?

One solution is to take the $\left\lfloor\log_3(N-1)\right\rfloor$. But how to calculate (preferentially in $O(1)$ time) the $M$, remaining into the integer arithmetic filed (summation, subtraction, multiplication, division, remainder and comparison)? Is this possible in $O(1)$ time?