From d88b3051ddd258ad5b5b82f613b95036fcb867ce Mon Sep 17 00:00:00 2001 From: Olivia Appleton Date: Thu, 12 Sep 2024 18:25:14 -0500 Subject: [PATCH] Refactor --- lua/src/lib/math.lua | 72 ++++++++++++++++++++++++-------------------- lua/src/p0015.lua | 4 +-- 2 files changed, 41 insertions(+), 35 deletions(-) diff --git a/lua/src/lib/math.lua b/lua/src/lib/math.lua index 6192f1b0..404d6604 100644 --- a/lua/src/lib/math.lua +++ b/lua/src/lib/math.lua @@ -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; @@ -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, } diff --git a/lua/src/p0015.lua b/lua/src/p0015.lua index 8932692e..b19690ec 100644 --- a/lua/src/p0015.lua +++ b/lua/src/p0015.lua @@ -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: --