-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwoSetsArray.java
107 lines (93 loc) · 3.12 KB
/
TwoSetsArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package two.sets.array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class TwoSetsArray {
/**
* Problem:You will be given two arrays of integers. You will be asked to 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
These numbers are referred to as being between the two arrays. You must determine how many such numbers exist.
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
int lcm = findLCM(a);
int finalCount = 0;
int[] b = new int[m];
for(int b_i=0; b_i < m; b_i++){
b[b_i] = in.nextInt();
}
int gcf = findGCF(b);
for(int i = lcm, j =2; i<=gcf; i=lcm*j,j++){
if(gcf%i==0){ finalCount++;}
}
System.out.println(finalCount);
}
static int findLCM(int arr[]){
int result = arr[0];
for (int i = 1; i < arr.length; i++) {
result = findLCM(result, arr[i]);
}
return result;
}
static int findLCM(int a,int b){
int min,max,lcm=1,x;
if(a>b){
max = a;
min = b;
}else{
max = b;
min = a;
}
for(int i=1;i<max;i++){
x = max*i;
if(x%min==0){
lcm = x;
break;
}
}
return lcm;
}
static int findGCF(int arr[]){
int result = arr[0];
for (int i = 1; i < arr.length; i++) {
result = findGCF(result, arr[i]);
}
return result;
}
static int findGCF(int a,int b) {
List<Integer> numberList = new ArrayList<Integer>();
numberList.add(a);
numberList.add(b);
Integer maxNumber = Collections.max(numberList);
// int minNumber = Collections.max(numberList);
int gcf = 1;
for (int i = maxNumber; i > 1; i--) { // taking max number for iterating loop
boolean check = false;
for (int j = 0; j < numberList.size(); j++) {
if (numberList.get(j) % i == 0) {
check = true;
} else {
check = false;
break;
}
}
if (check) {
for (int j = 0; j < numberList.size(); j++) {
numberList.set(j, numberList.get(j) / i);
}
gcf *= i;
maxNumber = Collections.max(numberList);
}
}
return gcf;
}
}