There will be two arrays of integers. Determine all integers that satisfy the following two conditions:
- The elements of the first array are all factors of the integer being considered
- The integer being considered is a factor of all elements of the second array
Example:
Input: n = 2, m=3,a[n]={2,4},b[m]={16,32,96}
Output: 3
Approach
Java
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;public class BetweenTwoSets {public static void main(String[] args) {int a[] = { 2, 4 }, b[] = { 16, 32, 96 };List<Integer> l1 = Arrays.stream(a).boxed().collect(Collectors.toList());List<Integer> l2 = Arrays.stream(b).boxed().collect(Collectors.toList());System.out.println(getTotalX(l1, l2));}public static int getTotalX(List<Integer> a, List<Integer> b) {int n = a.size();int m = b.size();int x = findlcm(a, n);int y = findGCD(b, m);int q = y / x;int no = 0;for (int i = 1; i <= q; i++) {if (q % i == 0) {no++;}}return no;}static int gcd(int a, int b) {if (a % b == 0)return b;elsereturn gcd(b, a % b);}static int findlcm(List<Integer> l, int n) {int ans = l.get(0);for (int i = 1; i < n; i++)ans = ((l.get(i) * ans) / gcd(l.get(i), ans));return ans;}static int findGCD(List<Integer> l, int n) {int result = l.get(0);for (int i = 1; i < n; i++)result = gcd(l.get(i), result);return result;}}
C++
#include <bits/stdc++.h>using namespace std;int gcd(int a, int b){if (a % b == 0)return b;elsereturn gcd(b, a % b);}long int findlcm(int arr[], int n){long int ans = arr[0];for (int i = 1; i < n; i++)ans = ((arr[i] * ans) /gcd(arr[i], ans));return ans;}int findGCD(int arr[], int n){int result = arr[0];for (int i = 1; i < n; i++)result = gcd(arr[i], result);return result;}int main(){int n = 2, m = 3, i, j, k, y, no = 0, q;long int x;int a[n] = {2, 4}, b[m] = {16, 32, 96};x = findlcm(a, n);y = findGCD(b, m);q = y / x;for (i = 1; i <= q; i++){if (q % i == 0){no++;}}printf("%d", no);return 0;}
No comments:
Post a Comment