GE (General Electric) Interview Question
Senior Software Development EngineersCountry: India
Interview Type: In-Person
Another way of looking at this.
You want the number of triples (i,j,k) such that n > i >= j >= k >= 0
Now if you consider the triple (i+2, j+1, k), then we have that n+1 >= i+2 > j+1 >k >= 0. Thus all we need to do is select 3 numbers among 0,1,2,..., n+2 and sort them, subtract 1 from the middle and 2 from the max to get our possible i,j,k.
Thus, the number is
n+1 choose 3.
Since temp starts out as 1, the answer is
1 + (n+1 choose 3)
I initially thought it to be n^2 + (n-1), but later realized this does not look to have a generic formula at least to me... for e.g. if n=2, temp will be 5, if n=3, temp will be 11, the above formula only works for n=2 and 3, but if n=4, temp = 21 (n^2 + (n+1)) and if n=5, temp = 36. So this does not look to have a generic formula.. Correct me if I'm wrong.
So, if n=2,3,4,5,6 ==> then temp = 5,11,21,36,57. Let me know if you folks see a formula here, it does not come to my head at this point :-).
1 + (1.2 + 2.3 + 3.4 + ... + n.(n+1))/2 is the pattern. Folks strong at math should help in giving .a formula.
Well my Math Says so.
1> Loop 1 runs upto (n-1)
2> Loop 2 runs upto (n-1)*n(Square)/2 , coz its summation where n is infact (n-1) here.
3> Loop 3 this is the most complex one, which my calculation shows whopping
((n-1)*n(Square))/4*((n-1)*n(Square)/2+1)
Now Final Formula is the Product of Loop 1 * Loop 2 * Loop 3 . Which is Strange ..
these situations are related to binomial theorem but exactly how its getting calculated need to check @aka
The answer is 1 + Summation ( Sum (i) ) where i = 1 to n
Adding 1 because, temp is initialized to 1.
So it will be 1 + Summation (i(i+1)/2) = 1 + (Summation(i^2) + Summation(i))/2 for i =1 to n
= 1+ [ ( n(n+1)(2n+1)/6 ) + ( n(n+1)/2 ) ] /2
And when simplified, gets to 1+ ( n(n+1)(n+2)/6 )
Java Code for the above algorithm.
public class CountForLoopUsingRecursion {
/**
* @param args
*/
//what is the value of temp for N
//int temp=0;
//for (int i = 0; i <N; i++) {
// for (int j = 0; j <=i; j++) {
// for (int k = 0; k <=j; k++) {
// temp++;
// }
// }
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(findLoopCount(1));
System.out.println(findLoopCount(2));
System.out.println(findLoopCount(3));
System.out.println(findLoopCount(4));
System.out.println(findLoopCount(5));
System.out.println(findLoopCount(6));
System.out.println(findLoopCount(7));
System.out.println(findLoopCount(8));
}
static int findLoopCount(int n)
{
if(n==1||n<=0)
{
return 1;
}
if(n==2)
{
return 4;
}
return (n*n)+findLoopCount(n-2);
}
}
1 + [Summation of i(i+1)/2 where i runs from 1 to n]
- Murali Mohan June 04, 2013Also, did a bit of math and found a closed form formula for this:
1 + [n(n+1)(2n+1) + 3n(n+1)]/12