Home ์ง์ˆ˜์˜ ํ•ฉ
Post
์ทจ์†Œ

์ง์ˆ˜์˜ ํ•ฉ

๐Ÿ”– ์ง์ˆ˜์˜ ํ•ฉ

๐Ÿ“Œ ๋ฌธ์ œ

๋ฌธ์ œ ์„ค๋ช…

์ •์ˆ˜ n์ด ์ฃผ์–ด์งˆ ๋•Œ, n์ดํ•˜์˜ ์ง์ˆ˜๋ฅผ ๋ชจ๋‘ ๋”ํ•œ ๊ฐ’์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.


์ œํ•œ์‚ฌํ•ญ

0 < n โ‰ค 1000


์ž…์ถœ๋ ฅ ์˜ˆ
nresult
1030
46

์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

์ž…์ถœ๋ ฅ ์˜ˆ #1

  • n์ด 10์ด๋ฏ€๋กœ 2 + 4 + 6 + 8 + 10 = 30์„ return ํ•ฉ๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ #2

  • n์ด 4์ด๋ฏ€๋กœ 2 + 4 = 6์„ return ํ•ฉ๋‹ˆ๋‹ค.

โœ๏ธ ํ’€์ด

1
2
3
4
5
6
7
8
9
10
function solution(n) {
    var answer = 0;
    
    for(let i = 0; i <= n; i++) {
        if (i % 2 === 0)
            answer += i;
    }
    
    return answer;
}

๋ฌธ์ œ๋ฅผ ๋ณด๋ฉด์„œ for ๋ฐ˜๋ณต๋ฌธ์„ ํ™œ์šฉํ•˜์—ฌ ํ’€๋ฉด ๋˜๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค. i๋ฅผ n๋งŒํผ ๋ฐ˜๋ณตํ•˜๊ณ , ์ง์ˆ˜๋งŒ์„ ๋”ํ•ด ๊ตฌํ•˜๋ฏ€๋กœ i % 2๋ฅผ ํ•˜์—ฌ ๋‚˜๋จธ์ง€๊ฐ€ 0์ธ ๊ฐ’๋“ค๋งŒ ๋”ํ•˜๋ฉด ๋œ๋‹ค.

๐Ÿ” ๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด

1
2
3
4
5
// ๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด
function solution(n) {
    var half = Math.floor(n/2);
    return half*(half+1);
}

์ด ๋ฐฉ์‹์€ n์„ Math.floor() ๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ํ‘ผ ๋ฐฉ์‹์ด๋‹ค. ๋งค๊ฐœ๋ณ€์ˆ˜ n์„ 2๋กœ ๋‚˜๋ˆ„๊ณ  ์†Œ์ˆ˜์  ์•„๋ž˜๋Š” ๋ฒ„๋ฆฐ๋‹ค. ํ›„์— ๋ฐ˜ ๊ฐ’๊ณผ ๋ฐ˜๊ฐ’+1์„ ๊ณฑํ•˜์—ฌ ์‰ฝ๊ฒŒ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

๐Ÿ’ป ์ถœ๋ ฅ ๊ฒฐ๊ณผ

image-20221123124013590

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

์–‘๊ผฌ์น˜

ํŠน์ • ๋ฌธ์ž ์ œ๊ฑฐํ•˜๊ธฐ