Between Two Sets – HackerRank Solution

Between Two Sets – HackerRank Solution

Problem :

You will be given two arrays of integers and asked to determine all integers that satisfy the following two conditions:

  1. The elements of the first array are all factors of the integer being considered
  2. The integer being considered is a factor of all elements of the second array

These numbers are referred to as being between the two arrays. You must determine how many such numbers exist.

For example, given the arrays a = [2, 6] and b = [24, 36], there are two numbers between them: 6 and 126 % 2 = 06 % 6 = 024 % 6 = 0 and 36 % 6 = 0 for the first value. Similarly, 12 % 2 = 012 % 6 = 0 and 24 % 12 = 036 % 12 = 0.

Function Description :

The first line contains two space-separated integers, n and m, the number of elements in array a and the number of elements in array b.

The second line contains n distinct space-separated integers describing a[i] where 0 <= i <= n.
The third line contains m distinct space-separated integers describing b[j] where 0 <= j <= m.

Constraints :

  • 1 <= n, m <= 10
  • 1 <= a[i] <= 100
  • 1 <= b[j] <= 100

Output Format :

Print the number of integers that are considered to be between a and b.

Sample Input :

2 3
2 4
16 32 96

Sample Output :

3

Explanation :

2 and 4 divide evenly into 4, 8, 12 and 16.
4, 8 and 16 divide evenly into 16, 32, 96.

4, 8 and 16 are the only three numbers for which each element of a is a factor and each is a factor of all elements of b.

Solution :

#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <map>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n, m;
    scanf("%d %d", &n, &m);
    int a[100], b[100];
    for (int i=0; i<n; i++)
        scanf("%d", &a[i]);
    for (int i=0; i<m; i++)
        scanf("%d", &b[i]);
    int cnt = 0;
    for (int k=1; k<=100; k++)
    {
        int flag = 1;
        for (int i=0; i<n; i++)
            if (k % a[i] != 0)
                flag = 0;
        for (int i=0; i<m; i++)
            if (b[i] % k != 0)
                flag = 0;
        if (flag == 1)
            cnt ++;
    }
    printf("%d\n", cnt);
    return 0;
}

 57 total views,  1 views today

Post Disclaimer

the above hole problem statement is given by hackerrank.com but the solution is generated by the SLTECHACADEMY authority if any of the query regarding this post or website fill the following contact form thank you.

Leave a Reply

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