如何从数组中找到除数最多的数字
我有一个数组,我想找到除数最多的数字。问题是我可以找到数字,但无法打印它是多少除数。
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);;
}
}
I have an array and i want to find number with most divisor. The problem is that i can find the number but i cant print how many divisor it is.
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);;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您只需检查
1
和n/2
之间的值即可找到n
的除数。您不会在n/2
和n
之间找到除数(n
本身除外)。这将有效地将您的执行时间减少一半。因此,您的除数查找方法可以像下面这样改进,以计算给定数字的除数数量。
然后,您需要迭代用户给出的
numbers
数组并找到每个数字的除数数。迭代时,您需要 2 个变量
currentMaxDivisors
- 存储迄今为止找到的最大除数numWithMaxDivisors
- 哪个数字具有上述除数数量如果您碰巧找到一个具有更多除数的新数字,您可以使用新值更新这些变量。最后,
numWithMaxDivisors
变量将包含具有最大除数的数字。First of all, you only need to check values between
1
andn/2
to find the divisors ofn
. You won't find a divisor betweenn/2
andn
(except forn
itself). This will effectively reduce your execution time by half.So your divisor finding method can be improved like below to count the number of divisors of a given number.
Then you need to iterate through the
numbers
array given by user and find the number of divisors for each number.While iterating you need 2 variables
currentMaxDivisors
- to store the max no of divisors you have found so farnumWithMaxDivisors
- which number had the above number of divisorsIf you happen to find a new number with more divisors, you update these variables with the new values. At the end,
numWithMaxDivisors
variable will contain the number with maximum divisors.