티스토리 뷰

알고리즘

1~100까지 합계 구하기

얗마 2016. 8. 27. 23:47

[방법 1]

- For문을 이용

 

--- 소스 ---

public class mainClass {
 
    public static void main(String[] args) {
 
        int total = 0;
        
        for ( int i = 1; i <= 100; i++ ) {
            
            System.out.println("total = " + "i(" + i + ")" + " + total(" + total + ")");
            total += i;
        }
        
        System.out.println("total: " + total);
}
cs



--- 결과 ---



[방법 2]

- 재귀 이용

 

--- 소스 ---

public class mainClass {
 
    public static void main(String[] args) {
 
        int num = 1;        
int total = 0;
        final int MAX = 100;
        
        System.out.println("최종 반환된 total: " + sum(num, total, MAX));
    }
 
    public static int sum(int num, int total, int MAX) {
        
        if ( total == MAX ) {
            return total;
        } else {
            total += num;
            System.out.println("합산한 total = " + total);
            total = sum(num, total, MAX);
        }
        
        return total;
    }
}

cs


--- 결과 ---



[방법 3]

- 가우스 등차수열의 합 공식 이용

 

--- 소스 ---

public class mainClass {
 
    public static void main(String[] args) {
 
        final int NUM = 1;        
        final int MAX = 100;
        int result = 0;
        
        result = ((NUM + MAX) * MAX) / 2;
        
        System.out.println("result: " + result);    }
}
cs


--- 결과 ---


 

[기타]

- 첫 번째 값을 임의의 숫자로 지정하여 합계 구하기

- 가우스 공식 응용

 

--- 소스 ---

public class mainClass {
 
    public static void main(String[] args) {
 
        final int NUM = 22;        
        final int MAX = 100;
        int result = 0;
        
        result = NUM > 1 ? ((NUM + MAX) * (MAX - (NUM - 1))) / 2 : ((NUM + MAX) * MAX) / 2;
        
        System.out.println("result: " + result);
}
cs


--- 결과 ---


'알고리즘' 카테고리의 다른 글

[코딩도장] 문자열 압축  (0) 2016.10.27
[코딩도장] Spiral Array  (0) 2016.10.26
[코딩도장] 숫자 개수 카운트  (0) 2016.10.25
[코딩도장] 제네레이터  (0) 2016.10.25
[Project Euler] Problem 001  (0) 2016.10.05
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/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
글 보관함