summaryrefslogtreecommitdiff
path: root/lua/day1.lua
blob: 08c170d03a827191d5d16ab2b7593827ba3e48b0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
-- Easy
function is_even(num)
   return num % 2 == 0
end

function is_prime(num)
   local res = true
   for i = 2,num-1 do
      if num % i == 0 then
         res = false
      end
   end
   return res
end

function print_first_n_primes(n)
   local p = 1
   while n ~= 0 do
      repeat
         p = p+1
      until is_prime(p)
      print(p)
      n = n-1
   end
end

-- Medium
function for_loop(a, b, f)
   while a < b do
      f(a)
      a = a+1
   end
end

-- Hard
function reduce(max, init, f)
   local tmp = init
   for i = 1,max do
      tmp = f(tmp, i)
   end
   return tmp
end

function factorial(n)
   return reduce(n, 1, function(x,y) return x*y end)
end