-
[프로그래머스 level.1] 3중반복문, 소수 판별식알고리즘 2023. 6. 21. 11:10
소수 만들기
function solution(nums) { let result = [], count = 0 for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { for (let k = j + 1; k < nums.length; k++) { let num = nums[i] + nums[j] + nums[k] if (isPrime(num)) { count += 1 } } } } return count; } const isPrime = (n) => { for (let i = 2; i <= Math.sqrt(n); i++) { if (n % i === 0) { return false; } } return true; }
삼중반복문 쓰기 싫지만 다 쓰고있어서 어쩔 수 없이 쓰게 되었다 좀 마음이 께림직하다....
소수를 구하는 공식은 간단하다 2부터 나의 제곱근?까지 나를 나누어보았을 때 나누어지지 않는다면 소수이며 나누어진다면 소수가 아니다. 그렇기에 나누어져서 몫이 없어지는 경우 소수가 아님을 말하듯 false를 return 하는 것이다
'알고리즘' 카테고리의 다른 글
[프로그래머스 알고리즘] while과 reduce의 합작 (0) 2023.06.21 [프로그래머스 알고리즘] 1~N까지 배열만들기, 제곱근의 갯수와 약수의 관계 (0) 2023.06.21 [프로그래머스 level.1] join(), split() (0) 2023.06.21 [프로그래머스 level.1] 내림차순정렬, 아스키코드 변환 (0) 2023.06.21 [프로그래머스 level.1] slice 스파르타 예습 (0) 2023.06.20