Manipulating divisible 3 and 5

Asked

Viewed 159 times

1

I have a statement that says I have to make a looping between 4 and 24, adding the index with a total value, with some points:

  1. If the index number is multiple of 5, it must add up to 3;
  2. If the index number is multiple of 3, it must subtract 4;
  3. If it is a multiple of 3 and 5, multiply the total value by 2;

The final result should be 190.

My code:

    public static void main(String[] args) {    
         int total = 0;

        for (int i = 4; i <= 24; i++) {

            //Somo o index com o valor total
            if ((i % 5 > 0) && (i % 3 > 0)) {
                total += i;
            }

            //Caso true a opção 3
            if ((i % 5 == 0) && (i % 3 == 0)) {
                total *= 2;
            }

            //Caso true a opção 2
            if (i % 3 == 0) {
                total -= 4;
            }

            //Caso true a opção 1
            if (i % 5 == 0) {
                total += 3;
            }

        }   
        System.out.println(total);
    }

} 

My result does not come out of 189, never to 190, I debugged but apparently my logic is right. What I can change to get to 190 correctly?

1 answer

1

As I understand it, options 1, 2, and 3 are exclusionary: only one of them must be executed.

But in your code, when the number is multiple of 5 and 3 at the same time, it falls in two if's: in what tests if it is multiple of 3 and 5 and then in what tests if it is multiple of 5.

But from what I understood of the statement, if it is multiple of 5 and 3, it should not enter the condition "only multiple of 5". Then just put a else in each if.

Another detail is that to check if a number is multiple of 5 and 3 at the same time, just check if it is multiple of 15:

int total = 0;
for (int i = 4; i <= 24; i++) {
    if (i % 5 > 0 && i % 3 > 0) {
        total += i;
    } else if (i % 15 == 0) {
        total *= 2;
    } else if (i % 5 == 0) {
        total += 3;
    } else if (i % 3 == 0) {
        total -= 4;
    }
}
System.out.println(total);

With that the result is 190.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.