Patryk Szymańczyk
Patryk Szymańczyk

Reputation: 37

how to find number with most divisor from array in java

I got some problem someone of with really helped me but I got program source 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 you know where is a problem ?

Upvotes: 1

Views: 299

Answers (2)

Aniketh Malyala
Aniketh Malyala

Reputation: 2660

The problem is that inside of your getNumWithMaxDivisors() method, you are not redefining the current number of max divisors. To fix this, you can update it inside of the if statement as 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; //ADD THIS LINE
            numWithMaxDivisors = numbers[i];
        }
    }
    return numWithMaxDivisors;
}

Input:

int[] numbers = {1,2,3,4,5};
System.out.println(getNumWithMaxDivisors(numbers));

Output:

4

Side Note: You could just as well start your for loop at i = 2 in your getNumDivisors() method, since every number is divisible by 1, so there is no point in checking it. This just saves you a bit of time!

Upvotes: 2

nikosidij
nikosidij

Reputation: 21

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;
}

Upvotes: 1

Related Questions