Hacker Rank : Dynamic Programming :Modified Fibonacci Series
Hacker rank - Dynamic Programming Part 1: Given the terms ti and t(i+1), term t(i+2) will be calculated
using the relation t(i+2)=ti+t(i+1)pow2
Algo:
Dictionery m;
m[1] =ti; m[2]=t(i+1)
function int fib(n)
{
for(i -> 1 to n)
{
if m[n]==null
return m[n]=fib[n-1]+fib[n+1]
else
return m[n];
}
}
using the relation t(i+2)=ti+t(i+1)pow2
Algo:
Dictionery m;
m[1] =ti; m[2]=t(i+1)
function int fib(n)
{
for(i -> 1 to n)
{
if m[n]==null
return m[n]=fib[n-1]+fib[n+1]
else
return m[n];
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string[] str=Console.ReadLine().Split(' ');
int[] a= new int[str.Length];
for(int i=0;i<str.Length;i++)
{
a[i]=Convert.ToInt32(str[i]);
}
Dictionary<int, BigInteger> m = new Dictionary<int, BigInteger>();
m[1] = a[0];
m[2] = a[1];
BigInteger sum = fib(a[2], m);
Console.WriteLine(m[a[2]]);
}
static BigInteger fib(int n, Dictionary<int, BigInteger> m_dic)
{
for (int i = 0; i < n; i++)
{
if (!m_dic.ContainsKey(n))
m_dic[n] = Pow((fib(n - 1, m_dic)),2) + fib(n - 2, m_dic);
}
return m_dic[n];
}
static BigInteger Pow(BigInteger a, int b)
{
if(b==0)
return 1;
else if(b==1)
return a;
else if (b % 2 == 1)
return a * Pow(a * a, b / 2);
return Pow(a*a,b/2);
}
}
}
Comments
Post a Comment