현재

뒤집은 소수 본문

알고리즘/기타알고리즘문제

뒤집은 소수

AAAge 2024. 4. 16. 20:44
설명

몇개를 출력할지 갯수를 정하고, 입력된 자연수를 뒤집었을때 320을 입력했을때 0은생략 23이소수인지 아닌지 확인한다

 

예시 입력 1 

9
32 55 62 20 250 370 200 30 100

예시 출력 1

23 2 73 2 3

 

<자체풀이>

더보기
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException{
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        for(int i = 0; i < a ; i++){
            String sb = new StringBuilder(sc.next()).reverse().toString();
            int temp = Integer.parseInt(sb);
            int count = 0;
            for( int x = 1; x <= temp ; x++){
                if( temp % x == 0){
                    count++;
                }
                if( count > 2){
                    break;
                }
            }
            if(count == 2){
                System.out.print(temp+ " ");
            }

            // int num = temp;
            // int length = 0;
            // while(temp > 0){
            //     temp = temp / 10;
            //     length++;
            // }
            // int list[] = new int[length];

        }
       
        sc.close();
    }
}

<정답풀이>

더보기
import java.util.*;
class Main {    
    public boolean isPrime(int num){
        if(num==1) return false;
        for(int i=2; i<num; i++){
            if(num%i==0) return false;
        }
        return true;
    }

    public ArrayList<Integer> solution(int n, int[] arr){
        ArrayList<Integer> answer = new ArrayList<>();
        for(int i=0; i<n; i++){
            int tmp=arr[i];
            int res=0;
            while(tmp>0){
                int t=tmp%10;
                res=res*10+t;
                tmp=tmp/10;
            }
            if(isPrime(res)) answer.add(res);
        }
        return answer;
    }
    public static void main(String[] args){
        Main T = new Main();
        Scanner kb = new Scanner(System.in);
        int n=kb.nextInt();
        int[] arr=new int[n];
        for(int i=0; i<n; i++){
            arr[i]=kb.nextInt();
        }
        for(int x : T.solution(n, arr)){
            System.out.print(x+" ");
        }
    }
}

'알고리즘 > 기타알고리즘문제' 카테고리의 다른 글

소수(에라토스테네스 체)  (0) 2024.04.16
12. 암호  (0) 2024.04.09
11. 문자열 압축  (0) 2024.04.08
10. 가장 짧은 문자거리  (0) 2024.04.08
8. 유효한 팰린드롬  (0) 2024.04.03