![[백준 / BOJ] 2581번 소수 (C++, Python)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FbnpCKx%2FbtrJk2udyak%2FjT07DmYPyL36e3c29IKKAk%2Fimg.png)
[백준 / BOJ] 2581번 소수 (C++, Python)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 4. 6. 03:23
Table of Contents
반응형
링크 : https://www.acmicpc.net/problem/2581
2581번: 소수
M이상 N이하의 자연수 중 소수인 것을 모두 찾아 첫째 줄에 그 합을, 둘째 줄에 그 중 최솟값을 출력한다. 단, M이상 N이하의 자연수 중 소수가 없을 경우는 첫째 줄에 -1을 출력한다.
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 <cmath> | |
#include <iostream> | |
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() { | |
int M, N, check = 0, res = 0, min; | |
cin >> M >> N; | |
for (int i = M; i <= N; ++i) { | |
if (isPrime(i)) { | |
res += i; | |
if (check == 0) { // 최솟값을 저장하기 위함 | |
min = i; | |
check++; | |
} | |
} | |
} | |
if (check == 0) // 소수가 아예 존재하지 않음 | |
cout << -1 << "\n"; | |
else | |
cout << res << "\n" << min << "\n"; | |
} |
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 = int(input()) | |
N = int(input()) | |
arr = [False, False] + [True] * 9999 | |
i = 2 | |
# 에라토스테네스의 체 | |
while i <= 10000: | |
if arr[i]: # 지워나가는 과정 | |
for j in range(i + i, 10001, i): | |
if arr[j]: | |
arr[j] = False | |
i += 1 | |
res = 0 | |
check = 0 | |
min = 0 | |
for i in range(M, N + 1): | |
if arr[i]: | |
res += i | |
if check == 0: | |
min = i | |
check = 1 | |
if check == 0: | |
print("-1") | |
else: | |
print(f"{res}\n{min}") |
소감
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 1929번 소수 구하기 (C++, Python) (0) | 2022.04.06 |
---|---|
[백준 / BOJ] 11653번 소인수분해 (C++, Python) (0) | 2022.04.06 |
[백준 / BOJ] 1978번 소수 찾기 (C++, Python) (0) | 2022.04.06 |
[백준 / BOJ] 10757번 큰 수 A + B (C++, Python) (0) | 2022.04.05 |
[백준 / BOJ] 2839번 설탕 배달 (C++, Python) (0) | 2022.04.05 |
@Reo :: 코드 아카이브
자기계발 블로그