-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAllGCD.java
More file actions
81 lines (60 loc) · 1.46 KB
/
AllGCD.java
File metadata and controls
81 lines (60 loc) · 1.46 KB
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
/*
ALL GCD
Given an array of integers A of size N.
Find and return how many distinct gcd( sub(A) ) values are possible, where sub(A) is any non-empty subsequence of arraya A.
NOTE: gcd here refers to greatest common divisor.
Input Format
The first argument given is the integer array A.
Output Format
Return how many distinct gcd( sub(A) ) values are possible, where sub(A) is any subsequence of array A.
Constraints
1 <= N <= 1000
1 <= A[i] <= 1000
For Example
Input 1:
A = [3, 2, 8]
Output 1:
4
Explaination 1:
gcd([3]) = 3
gcd([3, 2]) = 1
gcd([3, 8]) = 1
gcd([2]) = 2
gcd([2, 8]) = 2
gcd([8]) = 8
gcd([3, 2, 8]) = 1
There are 4 distinct gcd values (1,2, 3, 8).
Input 2:
A = [5, 17, 3, 11]
Output 2:
5
*/
public class Solution {
public int solve(int[] A) {
boolean[] arr = new boolean[1001];
for(int i=0;i<A.length;i++){
ArrayList<Integer> list = new ArrayList<>();
list.add(A[i]);
for(int j=0;j<arr.length;j++){
if(arr[j]){
list.add(gcd(A[i], j));
}
}
for(int elem:list){
arr[elem] = true;
}
}
int ans = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]){
ans++;
}
}
return ans;
}
public int gcd(int a, int b){
if(b==0)
return a;
return gcd(b, a%b);
}
}