# 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.
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://www.codingbroz.com/pentagonal-numbers-hackerrank-solution/", "fetch_time": 1723365188000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2024-33/segments/1722640983659.65/warc/CC-MAIN-20240811075334-20240811105334-00144.warc.gz", "warc_record_offset": 560160806, "warc_record_length": 65658, "token_count": 446, "char_count": 1602, "score": 3.65625, "int_score": 4, "crawl": "CC-MAIN-2024-33", "snapshot_type": "latest", "language": "en", "language_score": 0.6900781989097595, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00017-of-00064.parquet"}