Common Divisors – HackerRank Solution

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

Contents

First line of input contains an integer,Â `T`, which represent the number of test cases. Then followsÂ `T`Â lines. Each line contains two space separated integers,Â `M L`, representing the points earned by Mario and Luigi, respectively.

Input

First line of input contains an integer,Â `T`, which represent the number of test cases. Then followsÂ `T`Â lines. Each line contains two space separated integers,Â `M L`, representing the points earned by Mario and Luigi, respectively.

Output

For each test case, print the solution in different lines.

Constraints

• 1 <= T <= 10
• 1 <= L, M <= 10^8
• L, MÂ are integers

Sample Input

``````3
10 4
1 100
288 240``````

Sample Output

``````2
1
10``````

Explanation

Test Case #00:Â Divisors ofÂ M = 10Â areÂ {1,2,5,10}, while forÂ L = 4Â they areÂ {1, 2, 4}. SoÂ MÂ andÂ LÂ sharesÂ {1, 2}Â as their common divisors.

Test Case #01:Â Here asÂ M = 1, both players only share this number as their divisor.

Test Case #02:Â HereÂ MÂ andÂ LÂ sharesÂ 10Â integers,Â {1,2,3,4,6,8,12,16,24,48}, as their divisors.

=== codingbroz.com_728x90 (#88864) ===
=== codingbroz.com_728x90 (#88864) ===

Solution – Common Divisors – HackerRank Solution

Scala

```import java.util.Scanner

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

val t = sc.nextInt
(0 until t).foreach(_ => {
val a = sc.nextInt
val b = sc.nextInt

def divisors(n: Int): Set[Int] = {
def inner(v: Int): Set[Int] = if (v < 1) Set(n)
else if (n % v == 0) inner(v - 1) + v + n / v
else inner(v - 1)

inner(math.sqrt(n).toInt)
}

println(divisors(a).intersect(divisors(b)).size)
})
}
}
```

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