본문 바로가기

프로그래머스/lv0

약수 구하기

/* 약수 구하기
 * 정수 n이 매개변수로 주어질 때,
 * n의 약수를 오름차순으로 담은 배열을 return하도록 solution 함수를 완성해주세요.
 *
 * n    result
 * 24   [1, 2, 3, 4, 6, 8, 12, 24]  
 * 29   [1, 29]
 */
 
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
public class programmer_0_20 {
    static int a1 = 24
    static int a2 = 29;
 
    public ArrayList solution(int n) {
        ArrayList ar = new ArrayList<>();
 
        for(int i = 1; i <= n; i++){
            for(int k = 1; k <= n; k++){
                if(i * k == n){
                    ar.add(i);
                } 
            }
        }
        for(int i = 0; i < ar.size(); i++){
            System.out.println("i = " + i + " / " + ar.get(i));
        }
        int[] answer = new int[ar.size()];
        
        return ar;
    }
    public static void main(String args[]){
        programmer_0_20 t = new programmer_0_20();
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1));
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a2));
        System.out.println("---------------------------------------");
    }
}
cs

'프로그래머스 > lv0' 카테고리의 다른 글

가장 큰 수 찾기  (0) 2022.12.06
편지  (0) 2022.12.06
한 번만 등장한 문자  (0) 2022.12.05
인덱스 바꾸기  (0) 2022.12.05
영어가 싫어요  (0) 2022.12.05