java---试除法找到所有约数(每日一道算法2022.9.9)

题目
给定 n 个正整数 ai,对于每个整数 ai,请你按照从小到大的顺序输出它的所有约数

第一行包含整数 n
接下来 n 行,每行包含一个整数 ai

输入:
2
6
8
输出:
1 2 3 6
1 2 4 8
public class 约数_试除法判定 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m = in.nextInt();

        //调用以及输出处理
        while (m-- > 0) {
            int x = in.nextInt();
            ArrayList<Integer> res = find_divisor_op(x);
            for (int i : res) System.out.print(i + " ");
            System.out.println();
        }
    }

    //基础解法,如果能被整除,就说明i是n的约数,时间复杂度为O(n)
    public static ArrayList<Integer> find_divisor_base(int n) {
        ArrayList<Integer> q = new ArrayList<>();
        for (int i = 1; i<=n; i++) {
            if (n % i == 0) q.add(i);
        }
        return q;
    }

    //优化版本,i | n, n = i * j, j是一个整数,约数总是成对出现的,我们只需要找到较小的那个就能找到较大的那个
    //所以和找质数差不多,判断小于等于根号n的约数即可, 时间复杂度为O(根号n)
    public static ArrayList<Integer> find_divisor_op(int n) {
        ArrayList<Integer> q = new ArrayList<>();
        for (int i = 1; i <= n/i; i++) {
            if (n % i == 0) {
                q.add(i);
                if (i*i != n) {
                    q.add(n / i);     //特判防止类似2*2=4,添加两次2这种情况
                }
            }
        }
        Collections.sort(q);
        return q;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值