Skip to content

Instantly share code, notes, and snippets.

@AlbertMoscow
Created July 10, 2013 09:50
Show Gist options
  • Save AlbertMoscow/5965023 to your computer and use it in GitHub Desktop.
Save AlbertMoscow/5965023 to your computer and use it in GitHub Desktop.
The Prime Factors Kata implemented in elixir
defmodule PrimeFactors do
@moduledoc """
Inspired by Uncle Bob's algorithm:
http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata
"""
@doc """
Функция generate/1 получает целое число в качестве параметра
и возвращает все простые делители этого числа в виде списка.
"""
@spec generate(integer) :: list
def generate(n) do
generate(n, [], 2) |> Enum.sort
end
# The inner "while" cicle
defp generate(n, prime_factors, candidate) when rem(n, candidate) == 0 do
generate(div(n, candidate), [candidate|prime_factors], candidate)
end
# The outer "while" cicle
defp generate(n, prime_factors, candidate) when n > 1 do
generate(n, prime_factors, candidate + 1)
end
defp generate(_n, prime_factors, _candidate), do: prime_factors
end
ExUnit.start
defmodule PrimeFactorsTest do
use ExUnit.Case, async: true
test "generates all prime factors of a given number" do
Enum.each [ [[2], 2],
[[3], 3],
[[2,2], 4],
[[5], 5],
[[2,3], 6],
[[7], 7],
[[2,2,2], 8],
[[3,3], 9],
[[2,5], 10],
[[11], 11],
[[2,2,3], 12],
[[13], 13]
], fn [prime_factors, number] ->
assert prime_factors == PrimeFactors.generate(number)
end
end
end
@nhu313
Copy link

nhu313 commented Jul 15, 2013

It looks great! Very similar to Uncle Bob code. I like how you mark the methods private. I have to learn to do that. I also like how you did the sort. That is really cool. Does the code return it in descending order, is that why you have to sort it? I haven't started on mine. I've been super busy. Hopefully soon :)

@AlbertMoscow
Copy link
Author

Yes. You can see the order in this video:
http://youtu.be/TPcVx2yON-4
Thanks for kind words! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment