Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
LivInTheLookingGlass committed Sep 12, 2024
1 parent b2f3199 commit d88b305
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 35 deletions.
72 changes: 39 additions & 33 deletions lua/src/lib/math.lua
Original file line number Diff line number Diff line change
Expand Up @@ -16,41 +16,9 @@ local function n_choose_r(n, r)
end

-- slow path for big numbers// slow path for larger numbers
local factors = {}
local factors = factor_gen(n, r)
local answer
local tmp

-- collect factors of final number
for i = 2,n,1
do
factors[i] = 1
end

-- negative factor values indicate need to divide
for i = 2,r,1
do
factors[i] = factors[i] - 1
end
for i = 2,(n - r),1
do
factors[i] = factors[i] - 1
end

-- this loop reduces to prime factors only
for i = n,2,-1
do
for j = 2,(i - 1),1
do
if i % j == 0
then
factors[j] = factors[j] + factors[i]
factors[i / j] = factors[i / j] + factors[i]
factors[i] = 0
break
end
end
end

local i = 2
local j = 2
answer = 1;
Expand Down Expand Up @@ -93,6 +61,44 @@ local function n_choose_r(n, r)
return answer
end

local function factor_gen(n, r)
local factors = {}

-- collect factors of final number
for i = 2,n,1
do
factors[i] = 1
end

-- negative factor values indicate need to divide
for i = 2,r,1
do
factors[i] = factors[i] - 1
end
for i = 2,(n - r),1
do
factors[i] = factors[i] - 1
end

-- this loop reduces to prime factors only
for i = n,2,-1
do
for j = 2,(i - 1),1
do
if i % j == 0
then
factors[j] = factors[j] + factors[i]
factors[i / j] = factors[i / j] + factors[i]
factors[i] = 0
break
end
end
end

return factors
end

return {
factorial = factorial,
n_choose_r = n_choose_r,
}
4 changes: 2 additions & 2 deletions lua/src/p0015.lua
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
-- Turns out this is easy, if you think sideways a bit
--
-- You can only go down or right. If we say right=1, then you can only have 20 1s, since otherwise you go off the grid.
-- You also can't have fewer than 20 1s, since then you go off the grid the other way. This means you can look at it as a
-- bit string, and the number of 40-bit strings with 20 1s is 40c20.
-- You also can't have fewer than 20 1s, since then you go off the grid the other way. This means you can look at it as
-- a bit string, and the number of 40-bit strings with 20 1s is 40c20.
--
-- Problem:
--
Expand Down

0 comments on commit d88b305

Please sign in to comment.