Between Two Sets | HackerRank Solution | Using C/C++ Code4xU

 


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 12. 6%2 = 0, 6%6 = 0, 24%6 = 0 and 36%6 = 0 for the first value. Similarly, 12%2 = 0, 12%6 = 0 and 24%12 = 0, 36%12 = 0.

Function Description

Complete the getTotalX function in the editor below. It should return the number of integers that are betwen the sets.

getTotalX has the following parameter(s):

  • a: an array of integers
  • b: an array of integers

Input Format

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[j] where 0 <j < n.
The third line contains m distinct space-separated integers describing b[j] where 0 < j < m.

Constraints

  • < n, m < 10
  • < a[i] < 100
  • < 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:

Code in C

#include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ int m,n,flag,card,x,i,j; scanf("%d %d",&n,&m); int *a = malloc(sizeof(int) * n); for(int a_i = 0; a_i < n; a_i++){ scanf("%d",&a[a_i]); } int *b = malloc(sizeof(int) * m); for(int b_i = 0; b_i < m; b_i++) { scanf("%d",&b[b_i]); } card=0; for (x=1;x<=100;++x) { flag=1; for (i=0;i<n;++i) if ((x % a[i]) != 0) flag=0; for (j=0;j<m;++j) if ((b[j] % x) != 0) flag=0; if (flag == 1) ++card; } printf("%d\n",card); return 0; }


Code in C++

#include<bits/stdc++.h> #define ll long long int using namespace std; int main() { ll n,m; cin>>n>>m; ll a[n],b[m]; for(ll i=0;i<n;i++) cin>>a[i]; for(ll i=0;i<m;i++) cin>>b[i]; ll c=0; for(ll i=1;i<=100;i++) { bool ha=true,haa=true; for(ll j=0;j<n;j++) { if(i%a[j]!=0) { ha=false; break; } } for(ll j=0;j<m;j++) { if(b[j]%i!=0) { haa=false; break; } } if(ha && haa) { c++; } } cout<<c; return 0; }

 

Sajal Gupta

Hi, i am sajal.I am a hardworking engineering graduate specialised in Computer Science Engineering ... Along with my degree, I completed C/C++,.Net,Java and SQL courses From Youtube and Other sources and various technologies.I learnt helped me develop my final year project called Code4xU..

Post a Comment