문제 링크입니다: https://programmers.co.kr/learn/courses/30/lessons/12921
코딩테스트 연습 - 소수 찾기
1부터 입력받은 숫자 n 사이에 있는 소수의 개수를 반환하는 함수, solution을 만들어 보세요. 소수는 1과 자기 자신으로만 나누어지는 수를 의미합니다. (1은 소수가 아닙니다.) 제한 조건 n은 2이상
programmers.co.kr
에라토스테네스의 체를 이요하여 쉽게 풀 수 있는 문제였습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
using namespace std; | |
const int MAX = 1000000 + 1000; | |
int minFactor[MAX]; | |
void eratosthenes(void) | |
{ | |
minFactor[0] = minFactor[1] = -1; | |
for (int i = 2; i < MAX; i++) | |
{ | |
minFactor[i] = i; | |
} | |
for (int i = 2; i * i < MAX; i++) | |
{ | |
if (minFactor[i] != i) | |
{ | |
continue; | |
} | |
for (int j = i * i; j < MAX; j += i) | |
{ | |
if (minFactor[j] == j) | |
{ | |
minFactor[j] = i; | |
} | |
} | |
} | |
} | |
int solution(int n) { | |
eratosthenes(); | |
int answer = 0; | |
for (int i = 2; i <= n; i++) | |
{ | |
answer += (minFactor[i] == i); | |
} | |
return answer; | |
} |

개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > programmers' 카테고리의 다른 글
[Programmers] k진수에서 소수 개수 구하기 (0) | 2022.01.19 |
---|---|
[Programmers] 신고 결과 받기 (3) | 2022.01.16 |
[Programmers] 서울에서 김서방 찾기 (0) | 2021.12.18 |
[Programmers] 문자열 압축 (0) | 2021.12.10 |
[Programmers] 메뉴 리뉴얼 (0) | 2021.12.09 |