본문 바로가기

프로그래머스/lv1

약수의 합

/* 약수의 합
 * 정수 n을 입력받아 n의 약수를 모두 더한 값을 리턴하는 함수, solution을 완성해주세요.
 *
 * n    return
 * 12   28      1, 2, 3, 4, 6, 12입니다. 이를 모두 더하면 28
 * 5    6       6
 */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class programmer_1_8 {
    static int a1 = 12;     static int a2 = 5
    public int solution(int n) {
        int answer = 0;
        for(int i = 1; i <= n; i++){
            if(n%i == 0) answer += i;
        }
        return answer;
    }
    public static void main(String args[]){
        programmer_1_8 t = new programmer_1_8();
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(a2));
        System.out.println("---------------------------------------");
    }
}
 
cs

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

자릿수 더하기  (0) 2022.12.08
평균 구하기  (0) 2022.12.08
짝수와 홀수  (0) 2022.12.08
옹알이 (2)  (0) 2022.12.07
문자열 나누기  (0) 2022.12.07