Harry Whitelegg
Harry Whitelegg

Reputation: 1

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

Upvotes: 0

Views: 1085

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

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      
}

Upvotes: 1

hfontanez
hfontanez

Reputation: 6168

Your code

for (int i = n; i <= 1; i--) {
    remainder = multipliedDivisors / i;
    if (remainder == 0){
        answer = i;
        break;
    }

Decreases the counter from n down to 1. HOWEVER, your answer is not updated UNLESS remainder equals to zero. If that condition is never met, the default value of n will be returned (which is zero).

The problem? remainder = multipliedDivisors / i when will remainder be zero?
Because of this assignment, int multipliedDivisors = firstDivisor * secondDivisor;, only if one of the "divisor" variables is zero.

Redo your logic.

Upvotes: 0

Related Questions