An interesting mistake of ChatGPT

When asked to decompose a number into prime factors, ChatGPT produced:

defmodule PrimeFactors do
  def factors(n, divisor \\ 2) when divisor > n do
    [n]
  end
  def factors(n, divisor \\ 2) do
    if rem(n, divisor) == 0 do
      [divisor | factors(n / divisor, divisor)]
    else
      factors(n, divisor + 1)
    end
  end
end

It fails compilation since you cannot have two definitions with default values. I wonder if it worked in previous versions of Elixir?

1 Like

Since ChatGPT is interactive, I explained to it its error, it said I am right (it always says that!) and rewrote it… with the same error:

defmodule PrimeFactors do
  def factors(n, divisor \\ 2) when n <= 1 do
    []
  end
  def factors(n, divisor \\ 2) do
    if rem(n, divisor) == 0 do
      [divisor | factors(div(n, divisor), divisor)]
    else
      factors(n, divisor + 1)
    end
  end
end

(Note that it fixed by itself the small bug returning 1 as a prime factor.)

No, as far as I can recall this never worked in Elixir, because it semantically wouldn’t really make sense. Ah, ChatGPT… :smile:

3 Likes

I let you find the other bug (which ChatGPT fixed after I explained it, see the difference between the two codes).