Update a variable outside a loop from inside the loop
Trying to create a method to return the first number below "n" which can be entirely divided by both the first and second divisor. Currently my program is returning the default value of "answer" being 0, I want the value which is calculated within the loop to be translated outside the loop to be returned. Yes I am a beginner :(
static int highestNumberBelowNDivisibleByTwoNumbers(int firstDivisor, int secondDivisor, int n) {
int multipliedDivisors = firstDivisor * secondDivisor;
int answer = 0;
int remainder = 0;
for (int i = n; i <= 1; i--) {
remainder = multipliedDivisors / i;
if (remainder == 0){
answer = i;
break;
}
}
return answer;
}
Based on your description of:
Trying to create a method to return the first number below "n" which can be entirely divided by both the first and second divisor.
Try something more like below with the % operator (remainder/modulo):
static int highestNumberBelowNDivisibleByTwoNumbers(int firstDivisor, int secondDivisor, int n) {
while (n>0) {
if ((n % firstDivisor == 0) && (n % secondDivisor == 0)) {
return n;
}
n--;
}
return -1; // no answer found
}