# Pentagonal Numbers – HackerRank Solution

In this post, we will solve Pentagonal Numbers HackerRank Solution. This problem (Pentagonal Numbers) is a part of HackerRank Functional Programming series.

Pentagonal numbers are the number of dots that can be shown in a pentagonal pattern of dots. Let’s represent theÂ nthÂ pentagonal number byÂ P(n). The following figure depicts pentagonal patterns forÂ n âˆˆ {1, 2, 3, 4, 5}.

Your task is to find the value ofÂ P(n)Â for a givenÂ n.

## Input

The first line will contain an integerÂ T, which represents the number of test cases. ThenÂ TÂ lines, each representing a single test case, follow. Each test case contains an integerÂ n.

## Output

For each test case, print theÂ nthÂ pentagonal number,Â P(n), in separate line.

## Constraints

• 1 <=Â TÂ <= 105
• 1 <=Â nÂ <= 105

Sample Input

``````5
1
2
3
4
5``````

Sample Output

``````1
5
12
22
35``````

Explanation

Above image contains the pentagonal pattern for allÂ n‘s.

## Solution – Pentagonal Numbers – HackerRank Solution

Scala

```import java.util.Scanner

import scala.collection.mutable

object Solution {
private val data = mutable.Map[Int, Long]()

def p(n: Int): Long = data.getOrElseUpdate(n, if (n == 1) 1 else p(n - 1) + 3 * n - 2)

def main(args: Array[String]): Unit = {
val sc = new Scanner(System.in)

val t = sc.nextInt
(0 until t).foreach(_ => {
val n = sc.nextInt
println(p(n))
})

sc.close()
}
}
```

Note: This problem (Pentagonal Numbers) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.