【问题标题】:How to find Number with most divisor from array如何从数组中找到除数最多的数字
【发布时间】:2022-10-04 20:31:26
【问题描述】:

我有一个数组,我想找到除数最多的数字。问题是我可以找到这个数字,但我无法打印它是多少个除数。

static void printDivisors(int n)
{
    for (int i=1;i<=n;i++)
        if (n%i==0)
            System.out.print(i+" ");
}


public static void main(String args[])
{
    System.out.println("The divisors of 100 are: ");
    printDivisors(100);;
}

}

【问题讨论】:

  • 您应该包括您的尝试并描述您遇到的问题。见How to Ask

标签: java arrays integer-division


【解决方案1】:

首先,您只需检查1n/2 之间的值即可找到n 的除数。在n/2n 之间找不到除数(n 本身除外)。这将有效地将您的执行时间减少一半。

因此,您的除数查找方法可以改进如下,以计算给定数字的除数数量。

static int getNumDivisors(int n) {
    int noOfDivisors = 0;
    for (int i = 1; i <= n / 2; i++) {
        if (n % i == 0) {
            noOfDivisors++;
        }
    }
    if (n > 1) {
        noOfDivisors++; // n itself is a divisor of n
    }
    return noOfDivisors;
}

然后您需要遍历用户给出的numbers 数组并找到每个数字的除数。

迭代时需要 2 个变量

  • currentMaxDivisors - 存储到目前为止您找到的最大除数
  • numWithMaxDivisors - 哪个数字有上述除数

如果您碰巧找到一个具有更多除数的新数字,则使用新值更新这些变量。最后,numWithMaxDivisors 变量将包含具有最大除数的数字。

static int getNumDivisors(int n) {
    int noOfDivisors = 0;
    for (int i = 1; i <= n / 2; i++) {
        if (n % i == 0) {
            System.out.print(i + " ");
            noOfDivisors++;
        }
    }
    if (n > 1) {
        noOfDivisors++; // n itself is a divisor of n
    }
    return noOfDivisors;
}

static int getNumWithMaxDivisors(int[] numbers) {
    // Assuming numbers array has at least one element
    int currentMaxDivisors = 0;
    int numWithMaxDivisors = numbers[0];
    for (int i = 0; i < numbers.length; i++) {
        int numDivisors = getNumDivisors(numbers[i]);
        if (numDivisors > currentMaxDivisors) {
            numWithMaxDivisors = numbers[i];
        }
    }
    return numWithMaxDivisors;
}

public static void main(String[] args) {
    int[] numbers = new int[]{100, 55, 67, 2003, 12};
    int numWithMaxDivisors = getNumWithMaxDivisors(numbers);
    System.out.println(numWithMaxDivisors);
}

【讨论】:

  • 谢谢你,但对于前。我有数组 [ 5, 22, 21,8,10] 并打印出与以前相同的数字,我认为这是非常好的方法(如果我很好理解的话)它需要数组 [0] 并检查它有多少除数,比第二个循环需要数组 [1] 并且如果数组 [1] 的除数比 int currentMaxDivisor 多,对吗?
  • 对不起,我没完全明白你的问题。你能详细说明吗?
  • 好的,所以对于前。我有数组 [ 1, 2 , 3, 7, 20] (除数最多的数字是 20-1,2,4,5 等),我想得到 20,因为它是除数最多的数字。
  • 上面的getNumWithMaxDivisors 方法将为您提供该数组的20。无论如何,我已经删除了不必要的打印语句,因为您可能对它们感到困惑。请立即检查。
猜你喜欢
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 2016-12-17
  • 2014-04-18
  • 1970-01-01
  • 2011-10-31
相关资源
最近更新 更多