目录

AtCoder D 215

AtCoder

Leon | 24 Aug 2021

题目描述

题目中首先会给两个数分别是N和M

然后题目中会再给N个数

求1到M中与N互质的数。

思路

先将题目中的N个数分解质因数,排除掉每一个质因数的数,这样子剩下的数就是与所有数互质的数。

复杂度分析

给每一个数做因式分解 \(O(N\log N)\) 将每一个数排除 \(O(N)\) 故整体复杂度为 \(O(N\log N)\)

代码实现

import java.util.*;

public class coprime{
	public static ArrayList<Integer> factorize(int num){
		ArrayList <Integer> ans = new ArrayList<Integer>();
			if(num%2==0){
				while(num%2==0){
					num/=2;
				}
				ans.add(2);
			}
			for (int i = 3; i*i <= num; i++) {
				if(num%i==0){
					while(num%i==0){
						num/=i;
					}
					ans.add(i);
				}
			}
			if(num!=1) ans.add(num);
			//System.out.println(num+ " "+ans);
			return ans;

	}
	public static void main (String [] args){
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();
		int [] nums = new int [n];
		boolean [] factors = new boolean[100009];
		Arrays.fill(factors, true);
		for (int i = 0; i < nums.length; i++) {
			nums[i] = in.nextInt();
		}
		ArrayList <Integer> allTheF = new ArrayList<Integer>();
		for (int i = 0; i <nums.length; i++) {
			allTheF = factorize(nums[i]);
			for(int everyNum:allTheF){
				if(factors[everyNum]){
					for (int j = everyNum; j < factors.length; j+=everyNum) {
						factors[j] = false;
					}
				}
			}
		}
		int count = 0;
		for (int i = 1; i <= m; i++) {
			if(factors[i]) count++;
		}
		System.out.println(count);
		for (int i = 1; i <= m; i++) {
			if(factors[i]) System.out.println(i);
		}
	}
}

评论区