[c++,Swift] 프로그래머스 소수 찾기
by Roel Downey728x90
반응형
프로그래머스: 소수 찾기 -> 링크
이론 참고 :
2020/01/15 - [알고리즘_자료구조/이론정리] - 소수 구하기 - 에라토스테네스의 체
풀이
c++
#include <string>
#include <vector>
using namespace std;
int solution(int n) {
int *arr;
arr = new int[n+1];
int i = 2;
int result = 0;
for (i = 2; i <= n; i++)
{
arr[i] = i;
}
for (i = 2; i <= n; i++)
{
if (arr[i] == 0)
continue;
for (int j = i + i; j <= n; j += i)
{
arr[j] = 0;
}
}
for (i = 2; i <= n; i++)
{
if (arr[i] != 0)
result++;
}
return result;
}
Swift
func solution(_ n:Int) -> Int {
var arr = [Int].init(repeating: 0, count: n+1)
var result = 0
for index in 2...n {
arr[index] = index
}
for index in 2...n {
if arr[index] == 0 {
continue
}
var j = index + index
while(j <= n) {
arr[j] = 0
j += index
}
}
for index in 2...n {
if arr[index] != 0 {
result += 1
}
}
return result
}
728x90
반응형
'알고리즘_자료구조 > 문제풀이' 카테고리의 다른 글
[Java] 문자열 내 p와 y의 개수 (0) | 2020.03.02 |
---|---|
[Swift]프로그래머스 나누어 떨어지는 숫자 배열 (0) | 2020.01.16 |
[Swift]프로그래머스 2016 (0) | 2019.09.03 |
[Swift]프로그래머스 체육복 (0) | 2019.09.01 |
[Swift]프로그래머스 가운데 글자 가져오기 (0) | 2019.08.30 |
블로그의 정보
What doing?
Roel Downey