'how to find number with most divisor from array in java
i got some problem someone of with really helped me but i got a code who print all of divisor from array, but i tried to print a number with most divisor for ex. array[1,2,3,4,5] and i want to print that the number with most divisor is 4 ( 1,2,4)
public static class Main {
public static void main(String[] args) {
System.out.println(getNumWithMaxDivisors(numbers));
}
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++;
}
}
return noOfDivisors;
}
static int getNumWithMaxDivisors(int[] numbers) {
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;
}
}
Code looks that, do u know where is a problem ?
Solution 1:[1]
add this line of code currentMaxDivisors = numDivisors; inside your if-statement like so:
static int getNumWithMaxDivisors(int[] numbers) {
int currentMaxDivisors = 0;
int numWithMaxDivisors = numbers[0];
for (int i = 0; i < numbers.length; i++) {
int numDivisors = getNumDivisors(numbers[i]);
if (numDivisors > currentMaxDivisors) {
currentMaxDivisors = numDivisors; //here this is missing
numWithMaxDivisors = numbers[i];
}
}
return numWithMaxDivisors;
}
Solution 2:[2]
THANK U, both of u, it works but also i had to remowe this line
public static int getNumDivisors(int n) {
int noOfDivisors = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
noOfDivisors++;
System.out.print(i + " "); (THIS LINE)
}
}
return noOfDivisors;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nikosidij |
| Solution 2 | Patryk Szymańczyk |
