Home Posts Tags Post Search Tag Search

Post 41

Hacker Rank 15 - Pentagonal Numbers

Published on: 2025-06-14 Tags: elixir, Side Project, Hacker Rank
For this challenge we need to find the n'th Pentagonal Number for a list of n's.

In the beginning I was able to come up with a solution that worked for all test cases but didn't return fast enough for a large data set or a large enough n.

Ill put it here just for later knowledge. 

    def pentagon(1, _list), do: [1]
    def pentagon(2, _list), do: [5, 1]
    def pentagon(n, list) do
        [last | rest] = pentagon(n - 1, list)
        [n * 3 - 2 + last] ++ [last | rest]
    end

This uses previously set value and just adds in the new set of points around the top and right of the last pentagon.

Since this didn't work I did some research and found 2 things that helped me get the right values fast enough.

1. You can just compute the value of the n'th Pentagonal Number with P(n) = n * (3n - 1) / 2
2. :array can be used to store values in an array that has an O(1) for accessing any indexed value.

    def pentagon_array(n) do
      arr =
        Enum.reduce(1..n, :array.new(n), fn i, acc ->
          pent = div(i * (3 * i - 1), 2)
          :array.set(i - 1, pent, acc)
        end)
  
      arr
    end

This is simple using the above formula and understanding the way that you use the :array.
You will use the syntax :array.set(index, value, array)

So we are adding in a new element, index pair to the array.

    def map_pentagon_values([numbers, pentagon_array]) do
      Enum.map(numbers, fn i -> :array.get(i - 1, pentagon_array) end)
    end

Here is the syntax for the retrieval of the numbers
:array(index, array) is the simple syntax for the access.


As with all the other challenges Ill leave the print to the user.