![[백준 / BOJ] 1929번 소수 구하기 (C++, Python)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Fb67xvG%2FbtrJikhHa5q%2Fi4S9sHbHSPYUTFGY9DhaK0%2Fimg.png)
[백준 / BOJ] 1929번 소수 구하기 (C++, Python)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 4. 6. 23:08
Table of Contents
반응형
링크 : https://www.acmicpc.net/problem/1929
1929번: 소수 구하기
첫째 줄에 자연수 M과 N이 빈 칸을 사이에 두고 주어진다. (1 ≤ M ≤ N ≤ 1,000,000) M이상 N이하의 소수가 하나 이상 있는 입력만 주어진다.
www.acmicpc.net
문제

문제 풀이
이전에 포스팅했던 소수 찾기, 소수 문제들과 같은 맥락이다. 출력값만 조금 조정해주면 된다.
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 <cmath> | |
using namespace std; | |
// 원래는 루프를 2부터 나누어 n-1까지의 수 중 나머지가 0이 되는 수가 존재하는지 | |
// 판별해야 함. 하지만 너무 비효율적이기 때문에 루프 횟수를 줄여야 함. | |
// 제곱근까지만 반복해도 가능하다고 알려져 있음. | |
bool isPrime(int val) { | |
if (val < 2) | |
return false; | |
else { | |
for (int i = 2; i <= sqrt(val); ++i) { | |
if (val % i == 0) return false; | |
} | |
} | |
return true; | |
} | |
int main() { | |
ios::sync_with_stdio(false); | |
cin.tie(nullptr); | |
cout.tie(nullptr); | |
int M, N; | |
cin >> M >> N; | |
for (int i = M; i <= N; ++i) { | |
if (isPrime(i)) | |
cout << i << "\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
M, N = map(int, input().split()) | |
arr = [False, False] + [True] * (N - 1) | |
i = 2 | |
# 에라토스테네스의 체 | |
while i <= N: | |
if arr[i]: # 지워나가는 과정 | |
for j in range(i + i, N + 1, i): | |
if arr[j]: | |
arr[j] = False | |
i += 1 | |
for i in range(M, N + 1): | |
if arr[i]: | |
print(i) |
소감
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 9020번 골드바흐의 추측 (C++, Python) (0) | 2022.04.08 |
---|---|
[백준 / BOJ] 4948번 베르트랑 공준 (C++, Python) (0) | 2022.04.08 |
[백준 / BOJ] 11653번 소인수분해 (C++, Python) (0) | 2022.04.06 |
[백준 / BOJ] 2581번 소수 (C++, Python) (0) | 2022.04.06 |
[백준 / BOJ] 1978번 소수 찾기 (C++, Python) (0) | 2022.04.06 |
@Reo :: 코드 아카이브
자기계발 블로그