Answer:
import java.io.*;
public class Main {
public static void main(String[] args) {
int target = 20;
System.out.println(largestDivisor(target));
}
public static int largestDivisor(int value) {
int max = Integer.MIN_VALUE;
for (int i = 1; i < value; i++) {
if (value % i == 0) {
if (i > max) {
max = i;
}
}
}
if (max != Integer.MIN_VALUE) {
return max;
} else {
return 0;
}
}
}
Explanation:
Initialize a variable with the number for which you want to find the largest divisor.
In my case, I used target to denote the value.
I then created a method called largestDivisor that takes that value and evaluates it.
Since we want to find the largest divisor and not the smallest divisor, I created a variable called "max". Remember, if you want to find the maximum of an evaluation, use the minimum. If you want to find the minimum use the maximum.
We are using integers, so I used the Integer.MIN_VALUE constant which initializes the max variable as -2^31 (for the case of the minimum, it would be 2^31).
I then iterated over the length of the value (i < value), where it checks two conditions:
First: checks if the value is divisible by the value in i.
Secondly: checks if the value in i (which by then denotes the value that the number is divisible by) is greater than the maximum.
If so, assign the max variable to i.
Then, I check if we were able to find if the value was divisible by our verification, by adding a conditional statement that checks if the max is different from the minimum. If it is, that means it was able to find a value that was able to divide the target number.
If not, return 0, as the problem states.