# Lists and GCD – HackerRank Solution

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

You are given the elements of list,Â list, in the representation provided above. Find its greatest common divisor, i.e.,Â gcd(list).

## Input Format

First line contains an integer,Â q, which is the size of list,Â lst.
Then followsÂ qÂ lines, whereÂ ithÂ line represents the factors ofÂ ithÂ element ofÂ lst,Â li

## Output Format

Print one line representing the greatest common divisor ofÂ lstÂ (gcd(lst)) in the above representation.

## Constraints

• 2 <= q <= 1000
• All other integers lie inÂ [1, 105]
• 1 <=Â Total number of prime factors of an elementÂ <= 100

Notes

• Test cases are designed such thatÂ gcd(lst)Â will always be greater thanÂ 1.

Sample Input #00

``````2
7 2
2 2 7 1``````

Sample Output #00

``7 1``

Sample Input #01

``````4
2 2 3 2 5 3
3 2 5 3 11 1
2 2 3 3 5 4 7 6 19 18
3 10 5 15``````

Sample Output #01

``3 2 5 3``

Explanation

Test case #00:Â lst = {72, 22 x 71}. ThereforeÂ gcd(lst) = 71.
Test case #01:Â lst = {22 x 32 x 53, 32 x 53 x 111, 22 x 33 x 54 x 76 x 1918, 310 x 515} * gcd(lst) = 32 x 53.Â

## Solution – Lists and GCD – HackerRank Solution

Scala

```import java.util.Scanner

object Solution {

def main(args: Array[String]): Unit = {
case class Item(p: Int, n: Int) {
override def toString: String = s"\$p \$n"
}

val sc = new Scanner(System.in)

val Q = sc.nextInt
sc.nextLine
val items = (0 until Q).flatMap(_ => sc.nextLine.split(' ').map(_.toInt).grouped(2).map(arr => Item(arr.head, arr.last)))
.groupBy(_.p)
.map { case (p, list) => (p, list.length, list.map(_.n).min) }
.collect { case (p, Q, n) => Item(p, n) }
.toSeq
.sortBy(_.p)

println(items.mkString(" "))
sc.close()
}
}
```

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