目录

AtCoder D 215

AtCoder

djw | 23 Aug 2021

题目大意

题目会给N个数和M, 让我们列出1到M之间N个数中互质的数,以及其个数

思路

先找出N个数所有的质因数 , 再在1到M之间排除质因数的倍数 复杂度O(nlogn)

代码

import java.util.*;
import java.io.*;
public class abc215d{
    public static void factorize(int num, HashSet<Integer> set){
        for(int i = 2; i*i <= num; i++){
            while(num % i == 0){
                num /= i;
                set.add(i);
            }
        }
        if(num != 1) set.add(num);
    }
    public static void main(String[] args) throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));       
        String[] items = br.readLine().split(" ");
        int N = Integer.parseInt(items[0]);
        int M = Integer.parseInt(items[1]);
        items = br.readLine().split(" ");
        int[] arr = new int[N];
        boolean visited[] = new boolean[M+1];
        HashSet<Integer> factors = new HashSet<>(); 
        for(int n = 0; n < N; n++){
            arr[n] = Integer.parseInt(items[n]);
            factorize(arr[n], factors);
        }
        int time = M;
        for(int num : factors){
            for(int i = num; i <= M; i += num){
                if(visited[i]) continue;
                visited[i] = true;
                time--;
            }
        }
        System.out.println(time);
        for(int j = 1; j <= M; j++){
            if(!visited[j]) System.out.println(j);
        }
    }
}

评论区