[프로그래머스/C++]Lv.0 - 소인수분해

YH J·2023년 4월 18일
0

프로그래머스

목록 보기
42/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/120852

내 풀이

while에서 2부터 시작하여 나눠가는데 나머지가 나오면 나누는 수를 ++하고 나머지가 없으면 중복이 있는지 먼저 체크하고 없으면 answer에 추가한다. while조건은 n > 1이 더 나은것 같다.

내 코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(int n) {
    vector<int> answer;
    
    int a = 2;
    
    while(n != 1)
    {
        if(n % a == 0)
        {
            if(find(answer.begin(),answer.end(),a) == answer.end()) 
            {
                answer.push_back(a);
            }
            n /= a;
        }
        else
            a++;
    }
    
    
    
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

vector<int> solution(int n) {
    vector<int> answer;

    int ind = 2;
    while(n > 1)
    {
        if(n % ind == 0)
        {
            answer.emplace_back(ind);
            while(n %ind ==0)
            {
                n/=ind;
            }
        }
        ind++;
    }

    return answer;
}

다른 사람의 풀이 해석

일단 answer에 추가한 뒤 중복검사 없이 while을 또 돌려서 해당 숫자로 나누어 떨어지지 않을 때 까지 나눈다.

profile
게임 개발자 지망생

0개의 댓글