728x90
SMALL

using System;
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public int[] solution(int n) {
        List<int> list = new List<int>();
        
        for(int i=2;i<=n;i++)
        {        
            while(n%i==0)
            {
                list.Add(i);
                n = n/i; // list에 등록이 되었으니 나누어 주는 게 핵심인 듯.
            }   
        }
        
        int[] answer = list.Distinct().ToArray(); //중복되는 것들 삭제 한다.
        return answer;
    }
}

 

 

파이썬

/////////

 

def solution(n):
    answer = []
    d = 2
    while d <= n:
        if n % d == 0:
            n /= d
            if d not in answer:
                answer.append(d)
        else:
            d += 1
    return answer

 

////////

 

def solution(n):
    k = 2
    answer = []
    while n>1:
        if n%k==0:
            answer.append(k)
            while n%k==0:
                n//=k
        k+=1

    return answer

 

자바

///////

 

import java.util.*;

class Solution {
    public int[] solution(int n) {
        List<Integer> factorList = new ArrayList<>();
        
        for (int i = 2; i <= n; i++) 
        {
            if (n % i == 0) 
            {
                factorList.add(i);
                
                while (n % i == 0) 
                {
                    n /= i;
                }
            }
        }
        
        int[] answer = factorList.stream().mapToInt(i -> i).toArray();
        return answer;
    }
}

 

 

import java.util.*;
class Solution {
    public int[] solution(int n) {
       List<Integer> list = new ArrayList<>();
        int div = 2;
        
        while(n > 1)
        {
            if(n%div==0)
            {
                if(!list.contains(div))
                    list.add(div);
                n /= div;
                continue;
            }
            div++;
        }
        
        int[] answer = new int[list.size()];
        
        for(int i=0; i<answer.length; i++)
            answer[i] = list.get(i);
        
        return answer;
    }
}
728x90

설정

트랙백

댓글