sliver__

백준 - 베르트랑 공준(4948) 본문

CS/알고리즘

백준 - 베르트랑 공준(4948)

sliver__ 2021. 11. 18. 15:01
728x90

https://www.acmicpc.net/problem/4948

 

4948번: 베르트랑 공준

베르트랑 공준은 임의의 자연수 n에 대하여, n보다 크고, 2n보다 작거나 같은 소수는 적어도 하나 존재한다는 내용을 담고 있다. 이 명제는 조제프 베르트랑이 1845년에 추측했고, 파프누티 체비쇼

www.acmicpc.net

 

베르트랑 공준

 

주어진 숫자 n의 n+1부터 2n 사이의 소수의 개수를 세는 문제이다.

 

제출한 코드는 아래와 같습니다.

 

#include <iostream>
using namespace std;
#define MAX_VALUE 300001

int arr[MAX_VALUE];

void getPrime()
{
	arr[1] = 0;
	for (int i = 2; i*i < MAX_VALUE; i++)
	{
		for (int j = i+i; j <= MAX_VALUE; j += i)
		{
			if (arr[j] == 1) arr[j] = 0;
		}
	}
}

int count(int n)
{
	int res = 0;
	for (int i = n+1; i <= 2 * n; ++i)
	{
		if (arr[i] == 1) res++;
	}
	return res;
}

int main(void)
{
	for (int i = 0; i < MAX_VALUE; ++i) arr[i] = 1;
	getPrime();
	int n;
	do
	{
		cin >> n;
		if (n == 0) break;
		cout << count(n) << endl;
	} while (n != 0);
}

 

728x90

'CS > 알고리즘' 카테고리의 다른 글

백준 - 직사각형에서 탈출(1085)  (0) 2021.11.18
백준 - 골드바흐의 추측(9020)  (0) 2021.11.18
백준 - 소수 구하기(1929)  (0) 2021.11.18
백준 - 소인수분해(11653)  (0) 2021.11.18
백준 - 소수(2581)  (0) 2021.11.18
Comments