Jam's story

[프로그래머스] 약수의 합 본문

코딩테스트/프로그래머스

[프로그래머스] 약수의 합

애플쩀 2022. 8. 6. 18:16
import java.util.*;
 //n=12   -6까지검사       / n=15 - 7까지 검사 / n=16
//(1,12) (2,6) (3,4)    / (1,15) (3,5)     / (1,16) (4)
class Solution {
    public int solution(int n) {
        int answer = 0;
       
        if(n==1 || n==0){
            return n;
        }
        
       HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
            double root=Math.sqrt(n);

            if(n==Math.pow((int)root,2)) {
                answer+=1+n+(int)root;
                return answer;
            }
        
            for(int i=1; i<=n/2; i++){
               
                if(n%i==0){   
                   if(map.containsValue(i) ||map.containsKey(i)) continue;
                   else {
                     map.put(i,n/i);
                     answer+=i+(n/i);
                   }
                  
               } 
            }

        return answer;
    }
}

 

import java.util.*;
 //n=12   -6까지검사       / n=15 - 7까지 검사 / n=16
//(1,12) (2,6) (3,4)    / (1,15) (3,5)     / (1,16) (4)
class Solution {
    public int solution(int n) {
        int answer = 0;
       
        if(n==1 || n==0){
            return n;
        }
        
        ArrayList<Integer> list=new ArrayList<>();
        
        //제곱근일때
        double root=Math.sqrt(n);
            if(n==Math.pow((int)root,2)) {
                answer+=1+n+(int)root;
                return answer;
            }
        
            for(int i=1; i<=n/2; i++){
                if(n%i==0){   
                   if(list.contains(i)) continue;
                   else {
                     list.add(i);
                     list.add(n/i);
                     answer+=i+(n/i);
                   }
                  
               } 
            }

        return answer;
    }
}

 

 

처음에는 위에 코드 처럼 풀었는데 테스트12만 불통하는것이다.

이유를 생각해보니, 

64처럼 제곱수 뿐만아니라, 다른 약수들도 있을때( 64 1,64/ 2,32/ 4,16/ 8 ) 문제가 되는 것이다.

위의 코드는 제곱수면 제곱근 +1+n 하고 바로 리턴되니, 그래서 틀리는 것이다.

 

 

쉽게 생각하니, 풀리는 문제이다

 

import java.util.*;
 //n=12   -6까지검사       / n=15 - 7까지 검사 / n=16
//(1,12) (2,6) (3,4)    / (1,15) (3,5)     / (1,16) (4)
//64 1,64/ 2,32/ 4,16/ 8 
class Solution {
    public int solution(int n) {
        int answer=0;
        for(int i=1; i<=n; i++) {
            if(n%i==0) answer+=i;
        }
      return answer;
    }
      
}

 

 

다른 사람 풀이

  public int sumDivisor(int num) {
        int answer = 0;
            for(int i = 1; i <= num/2; i++){
        if(num%i == 0) answer += i;
      }
        return answer+num;
    }
Comments