From 82be0eb30df9c7d10749f4f75cd13a50437781a3 Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 25 Oct 2021 18:13:13 +0200 Subject: Lua solutions for week 136 --- challenge-136/abigail/README.md | 2 ++ challenge-136/abigail/lua/ch-1.lua | 42 ++++++++++++++++++++++++++++++++++++++ challenge-136/abigail/lua/ch-2.lua | 20 ++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 challenge-136/abigail/lua/ch-1.lua create mode 100644 challenge-136/abigail/lua/ch-2.lua diff --git a/challenge-136/abigail/README.md b/challenge-136/abigail/README.md index 6019a49bff..436e6a57e4 100644 --- a/challenge-136/abigail/README.md +++ b/challenge-136/abigail/README.md @@ -5,10 +5,12 @@ * [GNU AWK](awk/ch-1.gawk) * [Bash](bash/ch-1.sh) * [C](c/ch-1.c) +* [Lua](lua/ch-1.lua) * [Perl](perl/ch-1.pl) ## Part 2 * [AWK](awk/ch-2.awk) * [C](c/ch-2.c) +* [Lua](lua/ch-2.lua) * [Perl](perl/ch-2.pl) diff --git a/challenge-136/abigail/lua/ch-1.lua b/challenge-136/abigail/lua/ch-1.lua new file mode 100644 index 0000000000..182d18fba7 --- /dev/null +++ b/challenge-136/abigail/lua/ch-1.lua @@ -0,0 +1,42 @@ +#!/opt/local/bin/lua + +-- +-- See ../README.md +-- + +-- +-- Run as: lua ch-1.lua < input-file +-- + +-- +-- Find the GCD, using Euclids algorithm +-- (https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations) +-- +function gcd (a, b) + while b > 0 do + a, b = b, a % b + end + return a +end + +-- +-- Precalculate all the relevant powers of 2. Note that in pre 5-3 lua +-- integers are doubles, and start losing precision at 2^53, so we go +-- up to 2^52. +-- +local power_of_2 = {} +local power = 1 +for i = 1, 52 do + power = power * 2 + power_of_2 [power] = 1 +end + + +for line in io . lines () do + local _, _, n, m = line : find ("([0-9]+)%s+([0-9]+)") + if power_of_2 [gcd (tonumber (n), tonumber (m))] then + print (1) + else + print (0) + end +end diff --git a/challenge-136/abigail/lua/ch-2.lua b/challenge-136/abigail/lua/ch-2.lua new file mode 100644 index 0000000000..d403ce64d6 --- /dev/null +++ b/challenge-136/abigail/lua/ch-2.lua @@ -0,0 +1,20 @@ +#!/opt/local/bin/lua + +-- +-- See ../README.md +-- + +-- +-- Run as: lua ch-2.lua < input-file +-- + +function count (target, this_fib, prev_fib) + if target < this_fib then return 0 end + if target == this_fib then return 1 end + return (count (target - this_fib, this_fib + prev_fib, this_fib) + + count (target, this_fib + prev_fib, this_fib)) +end + +for line in io . lines () do + print (count (tonumber (line), 1, 1)) +end -- cgit