An equilateral
white triangle gets split into four equilateral sub-triangles and the one at
the center gets colored red. This process is repeated for all available white
squares in each iteration. You are given an integer m for the number of lines
following and an integer n in each line following that for the number of
iterations for each of which we want an answer.
For example n
= 1 Answer = 5
n = 2, Answer = 17
n = 3, Answer = 53 (?)
namespace TriangleCounter
{
class Program
{
static void Main(string[] args)
{
int n;
Int32.TryParse(Console.ReadLine(), out n);
for (int i = 0; i < n; i++)
{
int m;
Int32.TryParse(Console.ReadLine(), out m);
Console.WriteLine("{0}", GetTriangleCount(m));
}
}
static double GetTriangleCount(int m)
{
double white = 1;
double red = 0;
double result = 1;
for (int i = 0; i < m; i++)
{
red = white;
white = white * 3;
result = result + white + red;
}
return result;
}
}
}
We could also do this recursively as GetTriangleCountRecursive (n) = 3 * GetTriangleCountRecursive (n-1) + 1 + 1 and the terminating condition of n ==0 => 1
No comments:
Post a Comment