today's alogrithm

[BOJ] 기본수학 2 - JAVA

UR'im 2021. 1. 21. 19:31
  • 소수 찾기
  • 소수
  • 소인수 분해

▷소수 찾기 코드의 변화

www.acmicpc.net/problem/1978

 

1978번: 소수 찾기

첫 줄에 수의 개수 N이 주어진다. N은 100이하이다. 다음으로 N개의 수가 주어지는데 수는 1,000 이하의 자연수이다.

www.acmicpc.net

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int testCase = Integer.parseInt(br.readLine().trim());
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");
        
        int decimal = 0;
        for(int i = 0; i < testCase; i++){
            int n = Integer.parseInt(st.nextToken());    
            if(n >= 10 && n%2 == 1){
                for(int j = 2; j < n; j++){
                   if(n%j != 0){
                       decimal +=1;
                       continue;
                   }
                }
            }else if( n == 2 || n== 3 || n == 5 || n == 7 ) decimal +=1;
        }
        bw.write(decimal+"");
        bw.flush();
        bw.close();
        br.close();
    }
}

항상 소수 찾기 문제는 어려워했는데 역시나 첫도전은 틀렸다.

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int testCase = Integer.parseInt(br.readLine().trim());
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");
        
        int decimal = testCase;
        for(int i = 0; i < testCase; i++){
            int n = Integer.parseInt(st.nextToken());    
            if( n == 2 ) continue;
            else{
                for(int j = 2; j < n; j++){
                   if(n%j == 0){
                       decimal -=1;
                       continue;
                   }
                }
            }
        }
        bw.write(decimal+"");
        bw.flush();
        bw.close();
        br.close();
    }
}

이제 됬다 싶었는데 또 틀렸다,, 생각해보니까 1에 대한 말이 없었다.

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int testCase = Integer.parseInt(br.readLine().trim());
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");
        
        int decimal = testCase;
        for(int i = 0; i < testCase; i++){
            int n = Integer.parseInt(st.nextToken());    
            if( n == 2 ) continue;
            else if( n == 1 ) {
            	decimal -=1;
            	continue;
            }
            else{
                for(int j = 2; j < n; j++){
                   if(n%j == 0){
                       decimal -=1;
                       break;
                   }
                }
            }
        }
        bw.write(decimal+"");
        bw.flush();
        bw.close();
        br.close();
    }
}

최종 코드이다. else문 안에있는 for loop을 continue가 아니라 break로 바꿨다. continue로 해서 소수 아닌게 여러번 잡힌것이 문제 였다.

▷소수 코드의 변화

www.acmicpc.net/problem/2581

 

2581번: 소수

M이상 N이하의 자연수 중 소수인 것을 모두 찾아 첫째 줄에 그 합을, 둘째 줄에 그 중 최솟값을 출력한다.  단, M이상 N이하의 자연수 중 소수가 없을 경우는 첫째 줄에 -1을 출력한다.

www.acmicpc.net

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        List<Integer> decimal = new ArrayList<>();
        int num1 = Integer.parseInt(br.readLine());
        int num2 = Integer.parseInt(br.readLine());
        
        int min = num1 < num2 ? num1 : num2; 
        int max = num1 > num2 ? num1 : num2;
        
        int j ;
        for(int i = min; i < max; i++){
            for(j = 2; j <= i/2; j++){
                if(i % j == 0) break;
            }
            if( j == (i/2)) decimal.add(i);
        }
        
        if(decimal.isEmpty()) bw.write("-1");
        else{
            int sum = decimal.stream().mapToInt(Integer::intValue).sum();
            int minValue = Collections.min(decimal);
            bw.write(sum+"\n"+minValue);
        }
        
        bw.flush();
        bw.close();
        br.close();
    }
}

ArrayList를 사용해서 문제를 풀어보았다. 한줄로 sum과 min값을 구하고 싶어서 여러가지 찾아보게되었다.

그러나 역시나 틀렸다는 글을 보고 어디가 문제일까 싶었다.  두번 틀렸는데 지금 보니까 코드 수정 안하고 한번 더 돌린것 같다.

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        List<Integer> decimal = new ArrayList<>();
        int num1 = Integer.parseInt(br.readLine());
        int num2 = Integer.parseInt(br.readLine());
        
        int min = num1 < num2 ? num1 : num2; 
        int max = num1 > num2 ? num1 : num2;
        
        int j ;
        for(int i = min; i <= max; i++){
            for(j = 2; j <= i/2; j++){
                if(i % j == 0) break;
            }
            if( j-1 == i/2) decimal.add(i);
        }
        
        if(decimal.isEmpty()) bw.write("-1");
        else{
            int sum = decimal.stream().mapToInt(Integer::intValue).sum();
            int minValue = Collections.min(decimal);
            bw.write(sum+"\n"+minValue);
        }
        
        bw.flush();
        bw.close();
        br.close();
    }
}

최종 코드이다. for loop 안에서 decimal list에 값을 넣는 if 문을 잘못 작성했던것이 문제였다. j++ 때문에  j의 값이 i/2의 값보다 크기 때문에 if문이 씹힌것 이었다. 코드를 보면서 언제쯤 코드를 짧게 쓸 수 있을까 하는 생각이 든다..

▷소수 찾기 코드의 변화

www.acmicpc.net/problem/11653

 

11653번: 소인수분해

첫째 줄에 정수 N (1 ≤ N ≤ 10,000,000)이 주어진다.

www.acmicpc.net

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int num = Integer.parseInt(br.readLine().trim());
        int i = 2;
        while(num > 1){
            if(num % i == 0) {
                bw.write(i+"/n");
                num = num/i;
            }else{
                i++;
            }
        }
        
        bw.flush();
        bw.close();
        br.close();
    }
}

이 문제는 정말 바보같은 실수였다. 줄바꿈 문자인 \n를 /n으로 쓴것이 문제였다..

import java.io.*;
import java.util.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int num = Integer.parseInt(br.readLine().trim());
        int i = 2;
        while(num > 1){
            if(num % i == 0) {
                bw.write(i+"\n");
                num = num/i;
            }else{
                i++;
            }
        }
        
        bw.flush();
        bw.close();
        br.close();
    }
}

이것이 최종 코드이다.

오늘은 세문제를 풀어보았다.

한문제 더 풀까했지만 그냥 오늘은 여기서 마무리 지으려고 한다.. 

'today's alogrithm' 카테고리의 다른 글

[BOJ] 정렬 단계 - JAVA  (0) 2021.01.31
[프로그래머스] SQL고득점 Kit - oracle sql  (0) 2021.01.26
[BOJ] 재귀 단계 - JAVA  (0) 2021.01.24
[Programmers] SQL kit - Oracle  (0) 2021.01.23
코딩 테스트의 준비  (0) 2021.01.19