Lua: Divide a number by powers of 2

This question is parallel to python. How to factor a number into 2? ... Indeed, this is the same question, but instead of using Python (or Javascript or C ++ as they also exist), I'm wondering how this can be done using Lua. I have a very basic understanding of Python, so I took the code first listed on the site above and tried to translate it to Lua without success. Here's the original and then, my translation:

Python

def myfunc(x):
    powers = []
    i = 1
    while i <= x:
        if i & x:
            powers.append(i)
        i <<= 1
    return powers

      

Lua

function powerfind(n)
  local powers = {}
  i = 1
  while i <= n do
    if bit.band(i, n) then -- bitwise and check
      table.insert(powers, i)
    end
    i = bit.shl(i, 1) -- bitwise shift to the left
  end
  return powers
end

      

Unfortunately my version is blocking and "running out of memory". This was after using the number 12

as a test. It is more than likely that my primitive knowledge of Python is failing and I cannot properly translate the code from Python to Lua, so hopefully someone can offer a fresh set of eyes and help me fix this.

+3


source to share


2 answers


Thanks to the comments of user2357112, I've got this fixed, so I post an answer in case anyone else comes across this issue:



function powerfind(n)
  local powers = {}
  i = 1
  while i <= n do
    if bit.band(i, n) ~= 0 then -- bitwise and check
      table.insert(powers, i)
    end
    i = bit.shl(i, 1) -- bitwise shift to the left
  end
  return powers
end

      

+4


source


I saw that in other ways it became a kind of speed competition. It should also be easy to understand.

i is the current power. It isn't used for calculations.
n is the current place in the array.
r is the remainder after a division of x by two.

      

If the remainder is 1, then you know that i is a power of two, which is used in the binary representation of x.



local function powerfind(x)
    local powers={
        nil,nil,nil,nil,
        nil,nil,nil,nil,
        nil,nil,nil,nil,
        nil,nil,nil,nil,
    }
    local i,n=1,0
    while x~=0 do
        local r=x%2
        if r==1 then
            x,n=x-1,n+1
            powers[n]=i
        end
        x,i=x/2,2*i
    end
end

      

Running a million iterations, x from 1 to 1,000,000, takes me 0.29 seconds. I am initializing the size of the authority table to 16.

+4


source







All Articles