Algorithm of 11401 - counter

Problem Description Link
Algorithm:
You are given n rods of length 1, 2…, n. You have to pick any 3 of them & build a triangle. How many distinct triangles can you make? Note that, two triangles will be considered different if they have at least 1 pair of arms with different length.
To solve this problem you can follow this technique.
if we have a triangle with sides a,b,c therefore this must be true a+b>c , a+c>b , b+c>a

if n = 3
 we have 3 sticks
 1 2 3
 we can’t form any triangles with this
 if n = 4
 1 2 3 4
 we can form 1 triangle
 (2,3,4)
 if n = 5
 1 2 3 4 5
 we can form 3 triangles

(2,3,4)
 ——-
 (2,4,5)
 (3,4,5)
output[i]=output[i-1]+2*((n*(n+1))/2)-(!((i&1))*n);
((!(i&1))*n) if i is even this evaluates as n else it evaluates as 0
image

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience