Jam's story
[프로그래머스] 약수의 합 본문
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;
}
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 최대공약수와 최소공배수 (0) | 2022.08.10 |
---|---|
[프로그래머스] 이상한 문자 만들기 (0) | 2022.08.09 |
[프로그래머스] 시저 암호 (0) | 2022.08.05 |
[프로그래머스] 소수찾기 (0) | 2022.08.04 |
[프로그래머스] 서울에서 김서방 찾기 (0) | 2022.08.04 |