본문 바로가기
알고리즘/백준

[백준] 1747. 소수&팰린드롬

by vivi 2021. 10. 18.
import java.util.*;

class Main {

	public boolean isPrime(int N) {
		if (N == 1)
			return false;
		if (N == 2)
			return true;
		else if (N % 2 == 0)
			return false;
		else {
			int len = (int) Math.sqrt(N);
			for (int i = 3; i < len + 1; i++) {
				if (N % i == 0)
					return false;
			}
			return true;
		}
	}

	public boolean isPalindrome(int N) {
		if (N < 10)
			return true;
		String str = String.valueOf(N);
		int lt = 0, rt = str.length() - 1;
		while (lt < rt) {
			if (str.charAt(lt) != str.charAt(rt))
				return false;
			lt++;
			rt--;
		}
		return true;
	}

	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		int n = kb.nextInt();

		while (!(T.isPrime(n) && T.isPalindrome(n)))
			n++;

		System.out.print(n);
	}
}

 

isPrime 에서 루트N 까지 검사할 것, 루트 N-1 까지 검사하면 오답..

 

문제 출처 : https://www.acmicpc.net/problem/1747

 

1747번: 소수&팰린드롬

어떤 수와 그 수의 숫자 순서를 뒤집은 수가 일치하는 수를 팰린드롬이라 부른다. 예를 들어 79,197과 324,423 등이 팰린드롬 수이다. 어떤 수 N (1 ≤ N ≤ 1,000,000)이 주어졌을 때, N보다 크거나 같고,

www.acmicpc.net

 

 

추가

 

Math.sqrt함수는 실수 연산을 하기 때문에 반드시 오차가 생길 수밖에 없다. 따라서 아래와 같이 써아한다.

			for (int i = 2; i * i <= N; i++) {
				if (N % i == 0)
					return false;
			}

 

 

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

[백준] 5397. 키로거  (0) 2021.10.27
[백준] 1406. 에디터  (0) 2021.10.27
[백준] 15552. 빠른 A+B  (0) 2021.10.27
[백준] 1393. 음하철도 구구팔  (0) 2021.10.18
[백준] 1914. 하노이 탑  (0) 2021.10.08

댓글