-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerfectnumber.java
More file actions
43 lines (38 loc) · 1.26 KB
/
Copy pathPerfectnumber.java
File metadata and controls
43 lines (38 loc) · 1.26 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
package Day_09;
import java.io.*;
import java.util.*;
class Solution {
public ArrayList<Integer> perfect(int n) {
ArrayList<Integer> result = new ArrayList<>();
findPerfectNumbers(1, n, result);
return result;
}
public void findPerfectNumbers(int start, int end, ArrayList<Integer> result) {
if (start <= end) {
if (isPerfect(start, start - 1, 0)) {
result.add(start);
}
findPerfectNumbers(start + 1, end, result);
}
}
public boolean isPerfect(int num, int divisor, int sum) {
if (divisor == 0) {
return sum == num;
}
if (num % divisor == 0) {
sum += divisor;
}
return isPerfect(num, divisor - 1, sum);
}
}
public class Perfectnumber {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
// Reading N and K
String str = bufferedReader.readLine().trim();
int n = Integer.parseInt(str);
Solution solution = new Solution();
ArrayList<Integer> result = solution.perfect(n);
System.out.println(result);
}
}