const array1 = [1, 2, 3, 4 ,5 , 6, 7, 8];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4)); //2번째 ,3번째 index값 변경
// expected output: [1, 2, 0, 0]
fill에서 2번째 인자 값부터 3번째 인덱스 값을 포함하지 않는만큼 1번째 인자로 채운다
function solution(n){
let result = Array(n+1).fill(true).fill(false,0,2)
for(let i = 2; i*i <=n; i++){
if(result[i]){
for(let j=i*i; j<=n; j+=i){
result[j] = false;
}
}
}
return result.filter(el => el).length;
}
에라토스테네스의 체의 공식을 이용해서 푼 문제다.
기존 소수찾기방식으로는 런타임에러가 떠서 다른분들의 풀이를 찾아보니까
true로 index값 만큼 채우고 (n+1)
fill메소드로 0번째값(사용X)과 1번째 자리는 false로 채운 배열을 만든다
for문으로 2부터 돌기 시작해서 배열안의 인덱스값이 true라면 내부 for문으로 들어가
i(인덱스) x i(인덱스) 를 j초기값으로 준다
j가 배열보다 작거나 같을때까지 반복문이 실행되고 j에는 += i(인덱스 값을 더한다)
index값을 더해주면서 배수들은 다 False로 바꿔준다
for문을 다 돌고 남아있는 소수들의 길이를 리턴해준다
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
https://themarketer.tistory.com/73