首页 > 试题广场 >

无倍数数

[编程题]无倍数数
  • 热度指数:2020 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解

小M得到了n个互不相同的正整数ai,在这n个数中,某个数称为无倍数数当且仅当其他的数都不是它的倍数。请你帮小M找出这n个数中所有的无倍数数,并以升序输出。


输入描述:

第一行包含一个整数n。1≤n≤105

第二行包含n个互不相同的正整数Ai。1≤Ai≤107



输出描述:
按升序输出所有的无倍数数,以空格分隔。
示例1

输入

3
8 4 12

输出

8 12 
import java.util.*;

// Set记录, 枚举每个数的因数, 从Set移除
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[n];
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
            set.add(a[i]);
        }

        Arrays.sort(a); // 排序:从小到大
        for (int x : a) {
            for (int i = 2; i * i <= x; i++) { // 2开始, 剔除因数
                if (x % i == 0 && (set.contains(i) || set.contains(x / i) ) ) {
                    set.remove(i);
                    set.remove(x / i);
                }
            }
        }

        set.remove(1); // 1肯定不是, 下面处理结果升序即可
        List<Integer> res = new ArrayList<>(set);
        Collections.sort(res);
        StringBuilder sb = new StringBuilder();
        for (int x : res) sb.append(x).append(' ');
        System.out.println(sb.toString());
    }
}

发表于 2025-10-24 23:11:55 回复(0)