본문 바로가기
알고리즘(Java)/Array

[알고리즘]Array(배열) 6. 뒤집은 소수 - N개의 자연수가 입력되면 각 자연수를 뒤집은 후, 그 뒤집은 수가 소수이면 그 소수를 출력하기

by snowballchoi 2021. 7. 24.

6. 뒤집은 소수★
N개의 자연수가 입력되면 각 자연수를 뒤집은 후 그 뒤집은 수가 소수이면 그 소수를 출력하는 프로그램

입력) 첫 줄에 자연수의 개수 N(3<=N<=100)이 주어지고, 그 다음 줄에 N개의 자연수가 주어집니다. 
출력) 첫 줄에 뒤집은 소수를 출력합니다. 출력 순서는 입력된 순서대로 출력합니다.

 

 

1.

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	
	public static boolean isPrime(int res) {
		if (res==1) return false;
		for (int i=2; i<res; i++) {
			if (res%i==0) return false; // 약수 존재(소수X)
		}
		return true; // 소수O
	}
	
	public static ArrayList<Integer> solution(int n, int[] arr) {	
		ArrayList<Integer> answer = new ArrayList<>();
		
		// 뒤집기
		for (int i=0; i<n; i++) {
			int temp = arr[i];
			int res = 0;
			while (temp>0) { // temp가 0이 되면 break
				int t = temp%10; // 마지막 자리 숫자
				res = res*10+t;
				temp = temp/10; // 마지막 자리 숫자 제거
			}
			// 소수 검사
			if (isPrime(res)) answer.add(res);
		}		
		return answer;
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int[] arr = new int[n];
		for (int i=0; i<n; i++) {
			arr[i] = scanner.nextInt();
		}
		for (int x : solution(n, arr)) {
			System.out.print(x + " ");
		}
	}

}

 

2.

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	
	public static String solution(int n, String[] strArr) {
		String answer = "";		
		ArrayList<Integer> intArr = new ArrayList<Integer>(); // 뒤집은 숫자들
		
		// 뒤집기
		for (String x : strArr) {
			char[] c = x.toCharArray();
			int lt = 0, rt = x.length()-1;
			while (lt<rt) {
				char temp = c[lt];
				c[lt] = c[rt];
				c[rt] = temp;
				lt++;
				rt--;
			}
			x = String.valueOf(c);
			intArr.add(Integer.parseInt(x));
		}
		
		// 소수 검사
		for (int x : intArr) {
			int[] temp = new int[x+1]; // 다 0으로 초기화
			boolean isPrime = false;
			for (int i=2; i<x+1; i++) {
				if (temp[i]==0) { // 소수O
					isPrime = true;
					for (int j=i; j<x+1; j=j+i) {
						temp[j] = 1;
					}
				} else isPrime = false; // temp[i]==1 // 소수X
			}
			if (isPrime) answer += x + " ";
		}
        
		return answer;
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		String[] strArr = new String[n];
		for (int i=0; i<n; i++) {
			strArr[i] = scanner.next();
		}
		System.out.println(solution(n, strArr));
	}

}

결과

 

댓글