๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

[๋ฐฑ์ค€] 1773๋ฒˆ: ํญ์ฃฝ์‡ผ(๊ตฌํ˜„)

by ์ฃผ๋ฐœ2 2020. 5. 3.
๋ฐ˜์‘ํ˜•

https://www.acmicpc.net/problem/1773

 

1773๋ฒˆ: ํญ์ฃฝ์‡ผ

๋ฌธ์ œ ํ•™์ƒ๋“ค์€ 3์ฃผ๊ฐ€ ์ง€๋‚œ ๊ธฐ๋…์œผ๋กœ ๋งค์ ์—์„œ 1์›” 1์ผ์ด ์ง€๋‚˜ ์‹ธ๊ฒŒ ํŒŒ๋Š” ํญ์ฃฝ์„ ์‚ฌ์„œ ํ„ฐ๋œจ๋ฆฌ๊ณ  ์žˆ๋‹ค. ํญ์ฃฝ์‡ผ๋ฅผ ํ•˜๋Š” ๋™์•ˆ N๋ช…์˜ ํ•™์ƒ๋“ค์ด ํญ์ฃฝ์„ ํ„ฐ๋œจ๋ฆฐ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ด N๋ช…์˜ ํ•™์ƒ์€ ๊ฐ๊ฐ ์ผ์ •ํ•œ ์ฃผ๊ธฐ๋กœ ํญ์ฃฝ์„ ํ„ฐ๋œจ๋ฆฐ๋‹ค. ๋ฌผ๋ก  ์ด ์ฃผ๊ธฐ๋Š” ํ•™์ƒ๋“ค๋งˆ๋‹ค ๊ฐ™์„ ์ˆ˜๋„, ๋‹ค๋ฅผ ์ˆ˜๋„ ์žˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์šฐ๋ฆฌ๋Š” ์ดˆ ๋‹จ์œ„๋กœ ๊ด€์ฐฐ์„ ํ•˜๊ณ , ํญ์ฃฝ ์—ญ์‹œ ์ดˆ ๋‹จ์œ„๋กœ ํ„ฐ์ง„๋‹ค. ํญ์ฃฝ์‡ผ๊ฐ€ ๋๋‚  ๋•Œ๊นŒ์ง€ ์–ผ๋งˆ๋‚˜ ๋งŽ์€ ์‹œ๊ฐ„๋™์•ˆ ๋ฐคํ•˜๋Š˜์— ํญ์ฃฝ์ด ํ„ฐ์ง€๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋Š”์ง€ ๊ถ๊ธˆํ•ด ํ•˜๋Š” ์กฐ๊ต๋ฅผ ๋„์™€์ฃผ์ž

www.acmicpc.net

์ฝ”๋“œ

import java.util.Scanner;

public class Main {
	
	public static int solve(int N, int C, int[] arr) {
		int count = 0;
		
		for(int i=1; i<=C; i++) {
			for(int j=0; j<arr.length; j++) {
				if(i%arr[j] == 0) {
					count ++;
					break;
				}
			}
		}
		return count;
	}

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		int N = scan.nextInt();
		int C = scan.nextInt();
		int[] arr = new int[N];
		
		for(int i=0; i<N; i++)
			arr[i] = scan.nextInt();
		
		int count = solve(N, C, arr);
		System.out.println(count);
		scan.close();
	}

}

ํ’€์ด

์ œํ•œ์‹œ๊ฐ„์€ 2์ดˆ, N์˜ ๋ฒ”์œ„๋Š” 10,000 , C์˜ ๋ฒ”์œ„๋Š” 2,000,000 ์ด๋ฏ€๋กœ ์™„์ „ํƒ์ƒ‰์„ ํ•ด๋„ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค.

๋”ฐ๋ผ์„œ ํญ์ฃฝ์‡ผ๊ฐ€ ๋๋‚˜๋Š” ์‹œ๊ฐ„(C) ๊นŒ์ง€ ์™„์ „ ํƒ์ƒ‰์„ ํ†ตํ•ด, ๊ฐ๊ฐ์˜ ์ดˆ์— ํ•™์ƒ๋“ค์ด ํญ์ฃฝ์„ ํ„ฐ๋œจ๋ฆฌ๋Š” ์‹œ๊ธฐ๊ฐ€ ์กด์žฌํ• ๊ฒฝ์šฐ

count ๊ฐ’์„ 1์”ฉ ์ฆ๊ฐ€์‹œ์ผœ์ค€๋‹ค.

ํญ์ฃฝ์ด ๋™์‹œ์— ํ„ฐ์ง€๋Š” ๊ฒฝ์šฐ ํ•œ๋ฒˆ๋งŒ ์„ธ์•„๋ ค์•ผ ํ•˜๋ฏ€๋กœ, C๊นŒ์ง€ ์™„์ „ ํƒ์ƒ‰์„ ํ•˜๋ฉด์„œ arr๋ฐฐ์—ด(ํ•™์ƒ๋“ค์˜ ํญ์ฃฝ ์ฃผ๊ธฐ)์—

ํญ์ฃฝ์ด ํ„ฐ์ง€๋Š” ์ฃผ๊ธฐ๊ฐ€ ์žˆ์„๊ฒฝ์šฐ break๋ฅผ ํ†ตํ•ด ๋‹ค์Œ ์ดˆ๋ฅผ ํƒ์ƒ‰ํ•œ๋‹ค.

 

 

 

๋‹ค๋ฅธ ํ’€์ด

 

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

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String s = br.readLine();
		String str[] = s.split(" ");
		int n = Integer.parseInt(str[0]);
		int c = Integer.parseInt(str[1]);
		int crr[] = new int[c+1];
		int x=0;
		for(int i=0;i<n;i++){
			x = Integer.parseInt(br.readLine());
			for(int j=x; j<crr.length;j+=x){
				crr[j] = 1;
			}
		}
		int cnt = 0;
		for(int i=0;i<crr.length;i++){
			if(crr[i]==1){
				cnt+=1;
			}
		}
		System.out.println(cnt);

	}
}

์‹œ๊ฐ„์ด ๋Œ€๋žต 1/3์ •๋„ ๋‹จ์ถ•๋œ ์ฝ”๋“œ๋‹ค.

ํญ์ฃฝ ์ฃผ๊ธฐ์˜ ๋ฐฐ์ˆ˜๋ฅผ ๋ชจ๋‘ 1๋กœ ๋งŒ๋“ค๊ณ ,

ํญ์ฃฝ์ด ๋๋‚˜๋Š” ์‹œ๊ฐ„๊นŒ์ง€ ๋ฐฐ์—ด ๊ฐ’์ด 1์ธ๊ฒฝ์šฐ cnt๋ฅผ 1์”ฉ ์ฆ๊ฐ€์‹œํ‚ค๋Š” ์ฝ”๋“œ.

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€