Skip to content

Commit

Permalink
[gleam][prime-factors] use cons to add to list and reverse after
Browse files Browse the repository at this point in the history
  • Loading branch information
joaofnds committed Nov 11, 2024
1 parent 2d0acee commit 7a350f7
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions gleam/prime-factors/src/prime_factors.gleam
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import gleam/list

pub fn factors(value: Int) -> List(Int) {
do_factors(value, 2, [])
list.reverse(factors_iter(value, 2, []))
}

fn do_factors(n: Int, i: Int, factors: List(Int)) -> List(Int) {
case i <= n, n % i == 0 {
False, _ -> factors
_, True -> do_factors(n / i, i, list.append(factors, [i]))
_, False -> do_factors(n, i + 1, factors)
fn factors_iter(n: Int, i: Int, factors: List(Int)) -> List(Int) {
case n, n % i {
1, _ -> factors
_, 0 -> factors_iter(n / i, i, [i, ..factors])
_, _ -> factors_iter(n, i + 1, factors)
}
}

0 comments on commit 7a350f7

Please sign in to comment.