[23.07.14] 11653번 : 소인수분해

장서영·2023년 7월 14일
0

백준 알고리즘

목록 보기
5/6
post-thumbnail

백준 11653번 : 소인수분해

로직

  • 사용자에게 입력 받은 수를 N에 저장한다. ※ 만약 N이 1이면 출력 없이 끝낸다.
  • 2부터 시작해서 소수들로 N을 나눈다. → 값을 리스트에 저장
    • 소수들로 (나누어 떨어지게) 나누고 → 나온 몫으로 업데이트 했다가
    • 이 업데이트 된 걸로 또 나눈다.
  • 리스트를 출력한다.

python으로 풀어서..

N = int(input())
result = [] # 문자열로 하면 메모리 절약

if(N != 1):
    i = 2
    end = N
    while(end > 1):
        if(end % i != 0):
            i += 1
            continue
    
        result.append(i)
        end = end // i
    
    for i in result:
        print(i)

Javascript로 변경해 봤다.

let N = parseInt(prompt("Enter a number"));
let result = []; // Using array instead of string to save memory

if(N !== 1){
    let i = 2;
    let end = N;
    while(end > 1){
        if(end % i !== 0){
            i += 1;
            continue;
        }
        result.push(i);
        end = end / i;
    }
    for(let i = 0; i < result.length; i++){
        console.log(result[i]);
    }
}

모르는 거

1) 소수를 어떻게 구하는가..?

    while(N>1):
        for i in range(2, N+1):
            if N%i==0:
                print(i)
                N = N/i
                break # 다시 2부터 시작한다!
            }
        }

break가 핵심이었다..!

profile
하루살이 개발자

0개의 댓글