-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSharingCandies.java
More file actions
49 lines (46 loc) · 1.29 KB
/
SharingCandies.java
File metadata and controls
49 lines (46 loc) · 1.29 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
/*
* Complete the function below.
*/
static long getCandies(long n, long p) {
long count = 1;
long ans = 0;
Stack<Long> stack = new Stack<Long>();
boolean flag = false;
//Trivial case
if(p == 1) return 1;
for(long i = 2; i <= Math.sqrt(n); i++) {
if(n % i == 0) {
++count;
//push the quotient to stack
if((n / i) != i) {
stack.push(n/i);
}
}
//if found , break
if(count == p) {
ans = i;
flag = true;
break;
}
}
//still not found
if(!flag) {
while(count < p) {
//it means p > count
if(stack.isEmpty()) {
flag = false;
break;
}
ans = stack.peek();
stack.pop();
++count;
flag = true;
}
}
//A number also divides itself so count++
++count;
//If still not found set answer to number itself
if(!flag) ans = n;
//if count is still less than p, then ans = 0
return (p > count ? 0 : ans);
}