Finding divisors (with.Java)
This is an article about the problem of “finding divisors.”
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
When the integer n is given as a parameter, complete the solution function to return an array containing the divisors of n in ascending order.
Restrictions
- 1 ≤ n ≤ 10,000
Input/Output Example
n | result |
---|---|
24 | [1, 2, 3, 4, 6, 8, 12, 24] |
29 | [1, 29] |
My solution to the problem
class Solution {
public int[] solution(int n) {
int cnt = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0){
cnt++;
}
}
int[] answer = new int[cnt];
int idx = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0){
answer[idx++] = i;
}
}
return answer;
}
}
Solution explanation
- Declare the cnt variable and initialize it to 0. This variable is used to count the number of divisors.
- Execute a for statement that repeats from 1 to n. The variable i has values from 1 to n. If the remainder of dividing n by i is 0, that is, if i is a divisor of n, Increase the cnt value by 1.
- Declare an array answer of cnt length.
- Declare the idx variable and initialize it to 0. This variable points to an index in the answers array.
- Execute a for statement that repeats from 1 to n. The variable i has values from 1 to n. If the remainder of dividing n by i is 0, that is, if i is a divisor of n,
- Assign the value i to the idx index of the answer array and increase the idx value by 1.
- Returns an array of answers.