Had a browse around interview cake I like the site, anyway I got this weeks free practice problem. I did a recursive and iterative solution. I would change a few bits looking back at it now, as it is lacking any guard conditions for inappropriate input.
namespace boredbasics
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 10; i++)
{
Console.WriteLine(fib(i));
}
for (int i = 0; i <= 10; i++)
{
Console.WriteLine(fibRecursive(i));
}
Console.ReadLine();
}
public static int fibRecursive(int nthFib)
{
if ( nthFib == 0)
{
return 0;
}
else if ( nthFib == 1)
{
return 1;
}
else
{
return fibRecursive(nthFib - 1) + fibRecursive(nthFib - 2);
}
}
public static int fib(int nthFib)
{
if (nthFib == 0)
{
return 0;
}
else if (nthFib == 1 || nthFib == 2)
{
return 1;
}
else
{
int first = 1, second = 1, temp = 0;
for (int i = 2; i < nthFib; i++)
{
temp = first + second;
first = second;
second = temp;
}
return temp;
}
}
}
}
No comments:
Post a Comment