백준 2501

hong030·2023년 1월 30일
0

*solved.ac 기준 브론즈 3단계 문제

풀이)

  • 풀이 1:
    약수를 모두 구해 배열에 넣고 그 중 n번째 약수를 출력하는 방식으로 풀었다.
    시간을 최대한 줄이기 위해 BufferedReader을 활용했고 1~N/2 사이의 값으로만 for문을 활용해 약수를 구했다.
    배열 크기를 무조건 크게 하면 시간이 오래 걸리므로, string str에 약수를 붙인 다음 split으로 배열을 생성했다.

그러나 이러한 풀이는 약수를 모두 구해야 하기 때문에 시간이 필연적으로 오래 걸린다.

  • 풀이 2:
    위의 문제를 해결하기 위해 for문으로 약수를 구하되, n번째로 구하는 약수는 그 자리에서 바로 출력하고 break를 하는 방식으로 두 번째 풀이를 구했다.

내 코드)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
	public static void main(String[]args) throws IOException {
	
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String[] input= bf.readLine().split(" ");
		int big = Integer.parseInt(input[0]);
		int small = Integer.parseInt(input[1]);
		String str = "";
		for(int i = 1;i<=big/2; i++) {
			if (big % i == 0) {
				str = str + String.valueOf(i) + " ";
			}
			else
				continue;
		}
		str += String.valueOf(big);
		String strArr[] = str.split(" ");

		if(strArr.length < small) 
			System.out.println(0);
		else 
			System.out.println(strArr[small-1]);
		
	}
}

다른 풀이)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
	public static void main(String[]args) throws IOException {
	
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String[] input= bf.readLine().split(" ");
		int big = Integer.parseInt(input[0]);
		int small = Integer.parseInt(input[1]);
		int count = 0;
		
		for(int i = 1;i<=big;i++) {
			if (big % i == 0) {
				count ++;
				if(count == small) {
					System.out.println(i);
					break;
				}
			}
		}
		if(count < small)
			System.out.println(0);
		
	}
}
profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

0개의 댓글