1

Assume we have a number $ x $ in the following representation:

$$ x=\left(x_{n-1},...,x_{0}\right)=\sum_{i=0}^{n-1}x_{i}2^{i} $$

Each $x_i $ can be either $0 $ or $ 1 $. (Familier to the binary represantaion, but with finite constant number of digits, in our case - n digits).

I want to find a way to extract the minimum index $$ 0\leq j\leq n-1 $$ such that $ x_{j}\neq0 $ (In general $x_j$ can be either $0$ or $ 1 $ in this represantation).

For example, consider $n=4$ and $$ x=0101 $$. I want to find a way to "extract" the index 0.

I wanted to do the same thing and find the maximum index such that $x_i \neq 0 $, I'll show my work for this one and maybe it will help to understand what I want.

Given a number $ x=\left(x_{n-1},...,x_{0}\right) $, assume $m $ is the maximum index such that $x_m=1 $ (and for any $j>m$ we have $x_j=0$). So in order to extract $m $ we do the following:

We notice that $$ 2^{m}\leq\sum_{i=0}^{n-1}x_{i}2^{i}<2^{m+1} $$

So that $$ \log_{2}\left(2^{m}\right)\leq\log_{2}\left(\sum_{i=0}^{n-1}x_{i}2^{i}\right)<\log_{2}\left(2^{m+1}\right) $$

Thus, $$ m=\left\lfloor \log_{2}\left(\sum_{i=0}^{n-1}x_{i}2^{i}\right)\right\rfloor $$

Is there a similar way to find the minimum index $i $ such that $x_i \neq 0$?

Thanks in advance.

user26857
  • 52,094
FreeZe
  • 3,735

1 Answers1

1

What you are trying to compute is $\nu_2(x)$, the $2$-adic valuation of $x$, i.e. the highest exponent $\nu_2(x)$ such that $2^{\nu_2(x)}$ divides $x$ (see here).

If you want a "plain" math formula you can get this one:

$$\nu_2(x) = \log_2 \left[x - \sum_{k=0}^{\lfloor \log_2{x} \rfloor}\left(\left\lfloor\frac{2x-1+2^{k+1}}{2^{k+2}}\right\rfloor - \left\lfloor\frac{2x-1+2^{k+2}}{2^{k+3}}\right\rfloor - \left\lfloor \frac{x}{2^{k+2}} \right\rfloor\right)2^k \right] + \frac{1+(-1)^x}{2}$$

For an explanation see here.

However, the formula is much complicated, so just a curiosity and not for a practical use. To find $\nu_2(x)$ practically, just convert $x$ to its binary representation and loop through the $x_i$ coefficients till you find the first $x_i \neq 0$, as you already have done.