【问题标题】:First n divisors of a number一个数的前 n 个除数
【发布时间】:2018-09-20 21:25:30
【问题描述】:

这是一个非常简单的问题,但我遇到了麻烦。我想创建一个显示给定数字x 的第一个n 除数的方法。我选择创建一个数组来存储x 的所有倍数,然后你可以输入你想看到的数量。

例如,如果x = 20,那么我将拥有[1, 2, 4, 5, 10, 20],前4个将是1245

这是我写的:

public static String multOf(int x, int n){

    int[] divisors = new int[n];

    for (int i = 0; i < divisors.length; i++){
        for (int j = 1; j < x + 1; j++){
            if (j % x == 0)
                divisors[i] = j;
        }
    }   

    return Arrays.toString(divisors);
}

我认为有更好的方法可以做到这一点,但我想要一些关于我的解决方案的提示。

【问题讨论】:

  • 如果代码正常运行,您应该在 CodeReview 上发布。
  • 有什么东西不工作吗?

标签: java arrays for-loop


【解决方案1】:

错误是您根据需要多次循环整个搜索 - 每个结果一次。这非常贵。请注意,内部循环是代码,只需循环一次。随着每个匹配的数字要存储,您可以增加数组的索引来保存值。

  1. 您需要循环到数字的一半。
  2. 您只需循环一次。

给你:

public static String multOf(int x, int n) {
    int[] result = new int[n];                // To store the result
    int count = 0;                            // A counter to not exceed the 'n'
    for (int i=1; i<Math.round(x/2); i++) {   // The iteration starting from the zero
        if (x % i == 0) {                     // Is 'x' divisible by 'i'?
            result[count] = i;                // ... if so, save to the array
            count++;                          // ... and increment the index
        } if (count == n) {                   // If the limit has been reached
            break;                            // ... leave the iteration
        }
    }
    return Arrays.toString(result);           // Return the result
}

但是,在诸如multOf(20,9) 之类的调用的情况下,当除数的数量小于要求时,输出将类似于[1, 2, 4, 5, 0, 0, 0, 0, 0]

因此我建议使用List&lt;Integer&gt;:

public static String multOf(int x, int n) {
    List<Integer> list = new ArrayList<>();
    int count = 0;
    for (int i=1; i<Math.floor(x/2); i++) {
        if (x % i == 0) {
            list.add(i);
        } if (list.size() == n) {
            break;
        }
    }
    return list.toString();
}

现在,multOf(20,9) 调用将产生[1, 2, 4, 5]

真正痴迷于 Java 8 Stream API 的粉丝会这样做(但速度会慢一点):

public static String multOf(int x, int n) {
    return IntStream.rangeClosed(1, x/2)
                    .boxed()
                    .filter(i -> x % i == 0)
                    .limit(n)
                    .collect(Collectors.toList())
                    .toString();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-05
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2010-10-14
    相关资源
    最近更新 更多