![[백준 / BOJ] 4948번 베르트랑 공준 (C++, Python)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FJgDW2%2FbtrJp1O0iF4%2FL1KZFifG1coA4Almg6xMVk%2Fimg.png)
[백준 / BOJ] 4948번 베르트랑 공준 (C++, Python)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 4. 8. 17:15
Table of Contents
반응형
링크 : https://www.acmicpc.net/problem/4948
4948번: 베르트랑 공준
베르트랑 공준은 임의의 자연수 n에 대하여, n보다 크고, 2n보다 작거나 같은 소수는 적어도 하나 존재한다는 내용을 담고 있다. 이 명제는 조제프 베르트랑이 1845년에 추측했고, 파프누티 체비쇼
www.acmicpc.net
문제

문제 풀이
소수를 구하는 이전 문제들과 비슷한 맥락이지만 일일이 소수를 판별하는 알고리즘을 사용하면 시간 초과가 난다. 에라토스테네스의 체를 이용해야 한다. 잘 설명해주신 분이 있어 링크를 첨부한다.
https://maramarathon.tistory.com/39
소수 판별 알고리즘과 에라토스테네스의 체
소수 판별 알고리즘 소수 판별 알고리즘은 시간복잡도에 따라 다르게 구현 가능하다. 시간 복잡도 O(N) 소수란, 약수가 1과 자기자신 뿐인 수를 말한다. 따라서 N이 소수인지 판별하는 가장 쉬운
maramarathon.tistory.com
C++ 코드 전문
This file contains 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 <iostream> | |
#include <algorithm> | |
using namespace std; | |
bool arr[246913]; | |
void isPrime() { | |
int i = 2; | |
arr[0] = false; | |
arr[1] = false; | |
while (i <= 246912) { | |
if (arr[i]) | |
for (int j = i + i; j <= 246912; j += i) | |
if (arr[j]) | |
arr[j] = false; | |
i++; | |
} | |
} | |
int main() { | |
ios::sync_with_stdio(false); | |
cin.tie(nullptr); | |
cout.tie(nullptr); | |
int N; | |
cin >> N; | |
fill(arr, arr + 246913, true); | |
isPrime(); | |
while (N) { | |
int res = 0; | |
for (int i = N + 1; i <= 2 * N; ++i) | |
if (arr[i]) | |
res++; | |
cout << res << "\n"; | |
cin >> N; | |
} | |
return 0; | |
} |
Python 코드 전문
This file contains 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
arr = [False, False] + [True] * (246912 - 1) | |
i = 2 | |
# 에라토스테네스의 체 | |
while i <= 246912: | |
if arr[i]: # 지워나가는 과정 | |
for j in range(i + i, 246912 + 1, i): | |
if arr[j]: | |
arr[j] = False | |
i += 1 | |
while True: | |
N = int(input()) | |
if (N == 0): | |
break | |
res = 0 | |
for i in range(N + 1, 2 * N + 1): | |
if (arr[i]): | |
res += 1 | |
print(res) |
소감
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 4153번 직각삼각형 (C++, Python) (0) | 2022.04.09 |
---|---|
[백준 / BOJ] 9020번 골드바흐의 추측 (C++, Python) (0) | 2022.04.08 |
[백준 / BOJ] 1929번 소수 구하기 (C++, Python) (0) | 2022.04.06 |
[백준 / BOJ] 11653번 소인수분해 (C++, Python) (0) | 2022.04.06 |
[백준 / BOJ] 2581번 소수 (C++, Python) (0) | 2022.04.06 |
@Reo :: 코드 아카이브
자기계발 블로그