๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/์ž๋ฃŒ๊ตฌ์กฐ & ์•Œ๊ณ ๋ฆฌ์ฆ˜

1๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ํ•ฉ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

by 1mj 2021. 10. 13.

Q. ์ž์—ฐ์ˆ˜ n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ 1๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ํ•ฉ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ sum()์„ ๊ตฌํ˜„ํ•˜์‹œ์˜ค.

A1. ๋ฐ˜๋ณต๋ฌธ์„ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

for๋ฌธ ๋‚ด์—์„œ i๊ฐ€ 1๋ถ€ํ„ฐ 5๊นŒ์ง€ 1์”ฉ ์ฆ๊ฐ€ํ•˜๋ฉฐ result ๋ณ€์ˆ˜์— ๋ˆ„์ ํ•ฉ์„ ์ €์žฅํ•œ๋‹ค.

 

class Test {
    public static void main(String[] args) {
        System.out.println("1~5 ๊นŒ์ง€์˜ ํ•ฉ๊ณ„: " + sum(5));
    }
    
    public static int sum(int number) {
        int result = 0;
        for (int i = 1; i <= number; i++) {
            result += i;	// result = result + i์™€ ๋™์ผ
        }
        
        return result;
    }
}

 

i +=(์‚ฐ์ˆ  ํ›„ ํ• ๋‹น) ์—ฐ์‚ฐ ์ „ result +=(์‚ฐ์ˆ  ํ›„ ํ• ๋‹น) ์—ฐ์‚ฐ ํ›„ result
1 0 0+1
2 1 1+2
3 3 3+3
4 6 6+4
5 10 10+5

 

 

A2. ์žฌ๊ท€๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

n + ์žฌ๊ท€ํ•จ์ˆ˜(n-1)์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ํ˜ธ์ถœํ•œ๋‹ค.

n์ด 1์ด๋ฉด ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ข…๋ฃŒํ•˜๊ณ  ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

class Test {
    public static void main(String[] args) {
        System.out.println("1~5 ๊นŒ์ง€์˜ ํ•ฉ๊ณ„: " + sum(5));
    }
    
    public static int sum(int number) {
        if (number == 1) return 1;
        return number + sum(number - 1);
    }
}

 

sum(5) = 5 + 4 + 3 + 2 + 1

sum(4) = 4 + 3 + 2 + 1

sum(3) = 3 + 2 + 1

sum(2) = 2 + 1

sum(1) = 1

๋Œ“๊ธ€