<백준> 1747

진기명기·2026년 3월 12일

코딩테스트<C++>

목록 보기
170/212

소수&팰린드롬

문제
어떤 수와 그 수의 숫자 순서를 뒤집은 수가 일치하는 수를 팰린드롬이라 부른다. 예를 들어 79,197과 324,423 등이 팰린드롬 수이다.
어떤 수 N (1 ≤ N ≤ 1,000,000)이 주어졌을 때, N보다 크거나 같고, 소수이면서 팰린드롬인 수 중에서, 가장 작은 수를 구하는 프로그램을 작성하시오.

입력
첫째 줄에 N이 주어진다.

출력
첫째 줄에 조건을 만족하는 수를 출력한다.

bool isPalindrome(int index)
{
	string str = to_string(index);
	const char* c = str.c_str();

	int s = 0;
	int e = str.size() - 1;

	while (s < e)
	{
		if (c[s] != c[e])
		{
			return false;
		}
		s++;
		e--;
	}
	return true;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	long long n;
	cin >> n;

	long long arr[10000001];

	for (int i = 2; i < 10000001; i++)
		arr[i] = i;

	for (int i = 2; i <= sqrt(10000001); i++)
	{
		if (arr[i] == 0)
			continue;
		for (int j = i * i; j < 10000001; j += i)
		{
			arr[j] = 0;
		}
	}

	int num = n;

	while (true)
	{
		if (arr[num] != 0)
		{
			int result = arr[num];
			if (isPalindrome(result))
			{
				cout << result;
				break;
			}
		}
		num++;
	}
}

0개의 댓글