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.

Task

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.

Leave a Comment

Your email address will not be published. Required fields are marked *