Mark Spencers wrote:Remove if statement out of second for loop. Before this loop create variable When condition if (key.contains(query)) gives true you have to print key value pair,
make found true and use keyword break to exit loop.
Piet Souris wrote:@Jiyoung
if sum1 = a + b
and sum2 = a - b,
then sum1 - sum2 = 2b, and therefore even.
Now, if we have S5 = 1 + 2 + 3 + 4 + 5, and we change the sign of one digit in this series, the difference is an even number. So it is impossible to obtain 12 by changing zero or more signs in S5, since the difference 3 is an odd number.
Campbell Ritchie wrote:Actually, I think that you will find the solution will get easier and easier once you start thinking about triangular numbers
Campbell Ritchie wrote:In which case we can join the two topics back together.
Henry Wong wrote:. . . now you have two topics that are discussing the same thing. . . . Henry
Piet Souris wrote:Well, if you think about it, it is not that hard.
First of all, one needs to know the formula for the sum of 1, 2, 3, ..., N by heart, but we all do, don't we?
Then if you change the sign of any number in that series, the total sum decreases by an even number (why?).
Lets denote the sum 1 + 2 + ... + n with Sn.
Let's take the outcome of 12 as an example. We know thar S4 = 10, too low, so the next candidate is S5. But that sum is 15, and the difference with 12 is uneven. So S5 is impossible. Next xomes S6, being 21. The difference with 12 is again uneven, so S6 is also out of the question. S7? Well, the delta is 28 - 12 = 16, even and that can be formed by changing the signs of 1 and 7, or 2 and 6, or 3 and 5. Check: 1 - 2 + 3 + 4 + 5 - 6 + 7 = 12. So we have 7.
See the pattern? We only have to derive the general algorithm out of it. What if -12 is given?