Post

[Programmers] #120831 - 짝수의 합 [Java][C++][Python]

n 이하 짝수의 합을 구하는 워밍업 문제.

[Programmers] #120831 - 짝수의 합 [Java][C++][Python]

문제 링크


1. 아이디어

n 이하의 짝수를 모두 더한 값을 반환하면 되는 문제다. 2부터 n까지 2씩 증가시키며 순회해 값을 누적하면 짝수만 정확히 걸러 더할 수 있다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(1)$

($N$ = 입력값 n)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
class Solution {
    public int solution(int n) {
        int sum = 0;
        for (int i = 2; i <= n; i += 2) {
            sum += i;
        }

        return sum;
    }
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;

int solution(int n) {
    int sum = 0;
    for (int i = 2; i <= n; i += 2) {
        sum += i;
    }

    return sum;
}
1
2
def solution(n):
    return sum(range(2, n + 1, 2))

참고

등차수열 합 공식을 쓰면 $O(1)$에도 계산할 수 있다. 2부터 n까지의 짝수는 첫째항 $a_1=2$, 공차 $d=2$인 등차수열이고, 짝수 개수를 $m = \lfloor n/2 \rfloor$라 하면 합은 $m(m+1)$로 정리된다.


This post is licensed under CC BY 4.0 by the author.