[1002] Fly me to the Alpha Centauri _ node.js

λ°•μ„œν˜„Β·2023λ…„ 8μ›” 4일
0
post-thumbnail

🌡1002 Fly me to the Alpha Centauri


πŸ”»λ‚˜μ˜ 풀이

//남은 거리, μ œκ³±μˆ˜μΌλ•Œ
function sqrtDistance (x, y) {
    //남은 이동 거리
    const distance = y - x;
    //거리의 제곱근
    const squareRoot = Math.sqrt(distance);
    return squareRoot % 1 == 0 ? squareRoot * 2 - 1 : notSqrt(distance, squareRoot);

}

//거리가 μ œκ³±μˆ˜κ°€ μ•„λ‹ˆλΌλ©΄
function notSqrt (distance, squareRoot) {
    const ceilSqrt = Math.ceil(squareRoot);
    const floorSqrt = Math.floor(squareRoot)
    const median = ceilSqrt ** 2 - floorSqrt;
    return  distance < median ? floorSqrt * 2 : floorSqrt * 2 + 1;
}

function main () {
    // let input = require('fs').readFileSync('/dev/stdin').toString().split('\n');
    const input = require('fs').readFileSync('txt/1011.txt').toString().split('\n');
    const test = +input[0];

    for (let i = 1; i <= test; i++) {
        const [x, y] = input[i].split(' ').map(Number);
        const result  = sqrtDistance(x, y);
        console.log(result);
    }
}

main();

❗거리λ₯Ό μ œκ³±μˆ˜λ§ˆλ‹€ λ‚˜λˆ  λ¬Άμ–΄μ„œ λ³Έλ‹€.(제곱수 : squareRoot % 1 == 0)
 πŸ‘‰μ œκ³±μˆ˜μ˜ λ‹€μŒ μˆ«μžμ—μ„œ 이동 νšŸμˆ˜κ°€ μ¦κ°€ν•œλ‹€.
 πŸ‘‰λ¬ΆμΈ μˆ«μžλ“€μ˜ 쀑간값(median)μ—μ„œ 이동 νšŸμˆ˜κ°€ μ¦κ°€ν•œλ‹€.

0개의 λŒ“κΈ€