# 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 lstli

## 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.