재귀 | n까지의 합

Algorithm 2019. 8. 30. 14:59
반응형
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
32
33
34
35
36
37
using System;
 
namespace Application
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            //n까지의 합
            int n = 10;
            //result: 55
            var sol = new Solution();
            var result = sol.solution2(n);
            Console.WriteLine("result: {0}", result);
 
        }
    }
 
    public class Solution {
        public int solution1(int n) {
            int sum = 0;
            for (int i = 0; i < n; i++) {
                sum += i;
            }
            return sum;
        }
 
        
 
        public int solution2(int n) {
            if (n == 1return 1;
            return n + solution2(n - 1);
            
        }
    }
}
 
 
 
반응형

'Algorithm' 카테고리의 다른 글

프로그래머스 | 최소공배수  (0) 2019.09.06
삽입 정렬  (0) 2019.09.02
선택 정렬  (0) 2019.08.30
이진탐색 | 재귀  (0) 2019.08.30
소수구하기 | Prime Number | 에라토스테네스의 체  (0) 2019.08.30
: