0
I am feeling little bit difficult to understand this code.Will you please help me?
public class Problem_1_Multiples_Of_3_And_5 { /* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. */ public static void main (String[] args) { int sum = 0; boolean threeMultiple = false, fiveMultiple = false; for (int i = 3; i < 1000; i++) { threeMultiple = i % 3 == 0; fiveMultiple = i % 5 == 0; if (threeMultiple || fiveMultiple) sum += i; } System.out.println(sum); } }
8 Réponses
+ 1
Which part of the code you don't understand exactly?
+ 1
Sam Ir
As you know, the if statement will be executed if either or both of threeMultiple and fiveMultiple are true. Those variables are initialize as false before the loop so the if statement won't get executed by accident. Inside the loop, threeMultiple and fiveMultiple variables are assign based on i % 3 == 0 comparison and i % 5 == 0 comparison respectively. So it's actually similar to something like this
if (i % 3 == 0 || i % 5 == 0) {
...
}
+ 1
i=10
10 % 3 == 0 // is 10 divisible by three? no false
threeMultiple = false // store false to answer 1
10 % 5 == 0 // is 10 divisible by five ? yes true
fiveMultiple = true // store true to answer 2
// if answer1==true OR answer2==true
if (threeMultiple || fiveMultiple)
// yes it is true because answer2 is true
sum += 10 // add it to sum = sum + 10
+ 1
Agent_I
But how do threeMultiple or FiveMultiple get true before If statement?As both are declared false before loop...
+ 1
Sam Ir
Like I said, their assignment inside the loop
These two lines
threeMultiple = i % 3 == 0;
fiveMultuple = i % 5 == 0;
The value of threeMultiple is set according to this condition (i % 3 == 0) and the value of fiveMultiple us set according to this condition (i % 5 == 0). For example, after few iterations, the value of i will reach the value of, say 25. 25 % 3 == 0 is false, so threeMultiple value is now false, but 25 % 5 == 0 is true, so fiveMultiple is now true
0
I am confused how boolean is used ..
After first line inside main,there is:
boolean threeMultiple=false,fiveMultiple=false;
How is it used in if case inside for loop?
0
Agent_I
Oh!!I got it!!!
Thank you so much..I was very happy how quickly you answered my last question...Thank you so much Again....
0
zemiak
Thank you for help...