문제
나의 생각
약수가 3개 이상인 값들이 합성수이니 2중 for문으로 n이하 값들을 나누어 몫이 0 인값이 3개이면 answer을 증가시켜주는 방식으로 접근.
나의 답안
public static int solution(int n) {
int answer = 0;
for (int i = 1 ; i <= n ; i++){
int count = 0;
for(int j = 1; j <= i ; j++){
if (i % j == 0){
count++;
}
if (count == 3){
answer++;
break;
}
}
}
return answer;
}
다른 답안
IntStream에서 rangeClosed 사용하면 for문과 같이 사용가능.
filter를 사용하면 각 for문안에 조건을 걸듯이 사용가능.
import java.util.stream.IntStream;
class Solution {
public int solution(int n) {
return (int) IntStream.rangeClosed(1, n).filter(i -> (int) IntStream.rangeClosed(1, i).filter(i2 -> i % i2 == 0).count() > 2).count();
}
}
'Programmers 문제풀이 > Lv.0' 카테고리의 다른 글
모스부호 (1) (0) | 2023.02.28 |
---|---|
중복된 문자 제거 (0) | 2023.02.28 |
문자열 정렬하기 (2) (0) | 2023.02.28 |
숫자 찾기 (0) | 2023.02.28 |
369게임 (0) | 2023.02.28 |