AhmedLo - 1 year ago 155

Java Question

I have spent so much time trying to find the formula for this code, but still nothing .. I know the running time but the question really is, what if n = 100 for example, how many line of output will this code print? Is there any specific formula to get the count? The code I've done:

`int i, j, k;`

for (i = 1; i <= n; i++) {

for (j = i + 1; j <= n; j++) {

for (k = j + 1; k <= n; k++) {

System.out.println(i + " " + j + " " + k);

}

}

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

I have a feeling that you are requiring a **formula** to get number of iteration the nested loops will.

```
for( i = 1; i <= n; i++ )
for ( j = i+1; j <= n; j++ )
for( k = j+1; k <= n; k++ )
```

For those loops, the number of iterations will be:

```
(n*(n-1)*(n-2))/6, where n > 2.
```

**Generic formula** for above kind nested loops:

```
(n*(n-1)* ... *(n-r+1)) / r!, where n > r-1.
```

Here, r = number of nested loops

For example: when n = 20 and r = 3, number of iterations will be = (20*19*18) / 3! = 1140

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**