[프로그래머스/C++]Lv.0 - 약수 구하기

YH J·2023년 4월 17일
0

프로그래머스

목록 보기
16/168

문제 링크

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

내 풀이

1부터 n까지의 모든 숫자를 나눠서 나머지가 0이면 answer에 추가함

내 코드

#include <string>
#include <vector>

using namespace std;

vector<int> solution(int n) {
    vector<int> answer;
    for(int i = 1; i <= n; i++)
    {
        if(n%i == 0)
            answer.push_back(i);
    }
    return answer;
}

다른 사람의 풀이

#include <string>
#include <vector>

using namespace std;

vector<int> solution(int n) {
    vector<int> answer;
    for(int i = 1; i<=n/2; i++)
    {
        if(n % i == 0)
            answer.push_back(i);
    }
    answer.push_back(n);
    return answer;
}

다른 사람의 풀이 해석

약수는 n/2까지만 체크하면된다. 그러고 자기자신 n은 따로 추가

profile
게임 개발자 지망생

0개의 댓글