Elixir: bad argument in arithmetic expression when trying to add

1

I'm trying to get a program to return the collatz sequence to Elixir, but I get an ugly error that says

  

1) test a few basic test cases (CollatzTest)

 test/solution_test.exs:4

 ** (ArithmeticError) bad argument in arithmetic expression

 code: assert Collatz.collatz(3) == "3->10->5->16->8->4->2->1"

 stacktrace:

   (solution) lib/solution.ex:7: Collatz.collatz/1

   (solution) lib/solution.ex:8: Collatz.collatz/1

   (solution) lib/solution.ex:10: Collatz.collatz/1

   test/solution_test.exs:7: (test)

My code is as follows:

defmodule Collatz do

  def collatz(n) do
    cond do
      n == 1 ->
        "1"
      rem(n,2) == 0 ->
        "#{n}->#{collatz(n/2)}"
      true ->
        "#{n}->#{collatz(n*3+1)}"
    end
  end

end

Why is my error and how do I solve it?

    
asked by Ruslan López 05.01.2019 в 06:11
source

1 answer

2

The problem was that at some point in recursive calls I stopped working with integers, the solution is to force it to remain in the realm of integers, the most explicit solution I could find is to round the result so that it remains as whole.

round(n/2)
    
answered by 05.01.2019 / 07:20
source