I was puzzled with one of the question in Microsoft interview which is as given below:
A function should accept a range( 3 – 21 ) and it should print all the consecutive numbers combinations to form each number as given below:
3 = 1+2 5 = 2+3 6 = 1+2+3 7 = 3+4 9 = 4+5 10 = 1+2+3+4 11 = 5+6 12 = 3+4+5 13 = 6+7 14 = 2+3+4+5 15 = 1+2+3+4+5 17 = 8+9 18 = 5+6+7 19 = 9+10 20 = 2+3+4+5+6 21 = 10+11 21 = 1+2+3+4+5+6
could you please help me in forming this sequence in C#?
Thanks,
Mahesh
So here is a straightforward/naive answer (in C++, and not tested; but you should be able to translate). It uses the fact that
1 + 2 + … + n = n(n+1)/2,
which you have probably seen before. There are lots of easy optimisations that can be made here which I have omitted for clarity.