본문 바로가기

백준 문제풀기/JAVA

[백준 2501 JAVA 자바] 약수 구하기

N의 약수 중 K번째로 작은 수를 출력하시오

 

사실 해결방법은 문제에서 다 알려줍니다

6%1 = 0

6%2 = 0

6%3 = 0

6%4 = 2

 

나머지를 구하는 수식 %을 잘 이용합시다

 

코드입니다

 

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
    	
        int a = Integer.parseInt(st.nextToken());
        int b = Integer.parseInt(st.nextToken());

        int count = 0;
        int flag = 0;
        
        for(int i=1;i<=a;i++) {
        	
        	if (a%i==0) {
        		count+=1;
        		if(count==b) {
        			flag=1;
        			System.out.println(i);
        		}
        	}
        }
        
        if (flag==0) {
        	System.out.println(0);
        }
        
    }
}

 

flag를 이용해서

약수를 찾았는지

못찾았는지

확인했습니다