Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

코딩응급실

프로그래머스: 두 정수 사이의 합 본문

Java

프로그래머스: 두 정수 사이의 합

Daeryuk Kim 2024. 3. 2. 19:29
import java.util.*;

class Solution {
    public long solution(int a, int b) {
        int max = Math.max(a, b);
        int min = Math.min(a, b);

        return (long)(min + max) * (max - min + 1) / 2;
    }

    public static void main(String[] args) {
        int a = 3;
        int b = 5;
        Solution sol = new Solution();
        long result = sol.solution(a, b);
        System.out.println(result); // 출력: 12
    }
}

가우스 공식 사랑해요

보통 1~N 까지면 S = n * (n+1) // 2 이고,

N ~ M 까지면 S = (n+m) * (m-n+1) // 2 이다.