Issue
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);;
}
}
Solution
First of all, you only need to check values between 1
and n/2
to find the divisors of n
. You won't find a divisor between n/2
and n
(except for n
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.
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;
}
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 divisors
If 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.
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);
}
Answered By - Udith Gunaratna
Answer Checked By - Willingham (JavaFixing Volunteer)