๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
IT

[JavaScritpt] ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜, ์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜ ๊ตฌํ•˜๊ธฐ

by ITyranno 2023. 9. 1.
728x90
๋ฐ˜์‘ํ˜•

 

ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์„ธ๊ณ„๋ฅผ ํƒ๊ตฌํ•ฉ์‹œ๋‹ค.

 

 

 

[๋ฌธ์ œ]

 

21, 14์˜ ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜, ์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜๋ฅผ ๊ตฌํ•˜์—ฌ๋ผ.

 

 

 

[ํ’€์ด]

 

 

<์ตœ๋Œ€๊ณต์•ฝ์ˆ˜>

 

<body>
    <script>
        let a = 21, b = 14;
        let c = Math.min(a, b);
        console.log(c);
        for(let i = c; i >=1; i--) {
            if(a % i == 0 && b % i ==0){
                console.log(`์ตœ๋Œ€๊ณต์•ฝ์ˆ˜: ${i}`);
                break;
            }
        }

    </script>
</body>

Math.min์„ ํ†ตํ•ด ๋‘ ๋ณ€์ˆ˜ ์ค‘ ๋” ์ž‘์€ ๊ฐ’์„ ์ฐพ์Šต๋‹ˆ๋‹ค.

์ž‘์€ ๊ฐ’์—์„œ 1์”ฉ ๋นผ๋ฉด์„œ ๋‘˜์„ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‚˜๋จธ์ง€๊ฐ€ 0์ด ๋˜๋Š” ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ์ฐพ์Šต๋‹ˆ๋‹ค.

๊ทธ ๊ณผ์ •์—์„œ for ํ•จ์ˆ˜๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฐ˜๋ณต๋ฌธ์„ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.

์ตœ๋Œ€๊ณต์•ฝ์ˆ˜ 7์ด๋ผ๋Š” ๊ฒฐ๊ณผ๊ฐ’์„ ์–ป๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

 

 

 

<์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜>

 

<body>
    <script>
    let a = 21, b = 14;
        let c = Math.max(a, b);
        console.log(c);
        for(let i = c; i <= a * b; i++) {
            if(i % a == 0 && i % b ==0){
                console.log(`์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜: ${i}`);
                break;
            }
        }

    </script>
 </body>

 

Math.max์„ ํ†ตํ•ด ๋‘ ๋ณ€์ˆ˜ ์ค‘ ๋” ์ž‘์€ ๊ฐ’์„ ์ฐพ์Šต๋‹ˆ๋‹ค.

ํฐ ๊ฐ’์—์„œ 1์”ฉ ๋”ํ•˜๋ฉด์„œ ๋‘˜์˜ ๋ฐฐ์ˆ˜๊ฐ€ ๋˜๋Š” ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜๋ฅผ ์ฐพ์Šต๋‹ˆ๋‹ค.

๊ทธ ๊ณผ์ •์—์„œ for ํ•จ์ˆ˜๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฐ˜๋ณต๋ฌธ์„ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.

์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜ 42๋ผ๋Š” ๊ฒฐ๊ณผ๊ฐ’์„ ์–ป๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

 

[์ฐธ๊ณ ]

 

์ตœ๋Œ€๊ณต์•ฝ์ˆ˜(GCD) : Greatest Common Divisor

์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜(LCM) : Least Common Divisor

 

์œ ํด๋ฆฌ๋“œ ํ˜ธ์ œ๋ฒ• ์ด์šฉํ•œ ์ฝ”๋“œ

<body>
    <script>
        let a = 21, b = 14;
        function gcd(a, b) {
            if (a % b == 0){
                return b;
            }
            return gcd(b, a % b);
        }
        console.log(gcd(a, b));
        let ์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜ = a * b / gcd(a, b);
        console.log(์ตœ์†Œ๊ณต๋ฐฐ์ˆ˜);
        </script>
<body>

 

 

[์ด์ „ ๊ธ€ ์ฐธ๊ณ ]

 

2023.08.31 - [IT] - [JavaScript] ํŽ˜์ด์ง€page ์‹œ์ž‘ ๋ฒˆํ˜ธ์™€ ๋งˆ์ง€๋ง‰ ๋ฒˆํ˜ธ ๊ตฌํ•˜๊ธฐ

 

[JavaScript] ํŽ˜์ด์ง€page ์‹œ์ž‘ ๋ฒˆํ˜ธ์™€ ๋งˆ์ง€๋ง‰ ๋ฒˆํ˜ธ ๊ตฌํ•˜๊ธฐ

[๋ฌธ์ œ] ํ•œ ํŽ˜์ด์ง€์— ๋‚˜ํƒ€๋‚˜๋Š” ๊ฒŒ์‹œ๋ฌผ์˜ ์ˆ˜๊ฐ€ 10๊ฐœ์ด๊ณ , 1ํŽ˜์ด์ง€์˜ ๊ฒŒ์‹œ๋ฌผ ๋ฒˆํ˜ธ๋ฅผ 1๋ฒˆ~10๋ฒˆ์ด๋ผ๊ณ  ํ–ˆ์„ ๋•Œ, 17ํŽ˜์ด์ง€์˜ ๊ฒŒ์‹œ๋ฌผ ์‹œ์ž‘ ๋ฒˆํ˜ธ์™€ ๋งˆ์ง€๋ง‰ ๋ฒˆํ˜ธ๋ฅผ ๊ตฌํ•˜์‹œ์˜ค. [ํ’€์ด] let ํŽ˜์ด์ง€ = 17; let ๋งˆ์ง€๋ง‰

ityranno.tistory.com

 

2023.08.31 - [IT] - [JavaScript] ๋ฌธ์ž ๋ถ„๋ฆฌํ•ด์„œ ์ถœ๋ ฅํ•˜๊ธฐ

 

[JavaScript] ๋ฌธ์ž ๋ถ„๋ฆฌํ•ด์„œ ์ถœ๋ ฅํ•˜๊ธฐ

[๋ฌธ์ œ] "Life" is too short, You need 'JavaScript' ๋ฌธ์žฅ์„ ๋ถ„๋ฆฌํ•˜์—ฌ ์ถœ๋ ฅํ•˜๋ผ. [ํ’€์ด] let text = '\"Life\" is too short, \nYou need \'JavaScript\''; console.log(text.split(' ')); console.log(text); ๋ฌธ์ž๋ฅผ ๋ถ„๋ฆฌํ•˜์—ฌ ๋ฐฐ์—ด๋กœ ์ €์žฅํ•˜๊ธฐ

ityranno.tistory.com

 

 

 

728x90
๋ฐ˜์‘ํ˜•

loading