• + 11 comments

    My only concern is problem focusses on handling very large numbers rather than putting it under DP

    • + 1 comment

      I agree. Choose a language that has large number support and you can just translate the formula into code and are done. It becomes almost as simple as hello world.

      • + 2 comments

        I want to code in c itself. Any way out ?

        • + 3 comments

          Yes, Write functions for string multiplication and summation.

          • + 1 comment

            how to do that... plz can u explain??

            • + 5 comments

              use double to declare data type as double a ,b,c; while scaning scanf("%lf",&a); while printing printf("%0.lf",a); // 0.lf restricts the decimal point to zeroth position which is an integer

              • + 1 comment

                thank you.. thanks allloott... :)

                • + 0 comments

                  Very easy problem for python users.

                  Hackerrank - Fibonacci Modified Solution

              • + 2 comments

                i tried that too. even used long double. that's not working.. can u explain?

                • + 1 comment

                  in second test case its a 20 digit and crossing number soo long double is not enough to perform tis programme

                • + 0 comments

                  u have to convert number into array/string, like if number is 543656 then store it in array like |3|4|3|6|5|6|. then write seperate function to add and multiply these array/string and then try to find out fibo.

              • + 2 comments

                can u help? what is wrong with this????

                void fibonacciModified(double t1, double t2, double n) { int i; double arr[20]; arr[0]=t1; arr[1]=t2; for(i=2;i<20;i++) { arr[i]=t1+t2*t2; t1=t2; t2=arr[i]; } for(i=0;i<20;i++) { if((i+1)==n) printf("%0.lf",arr[i]); } }

                • + 0 comments

                  double will not work.. The no. is too large. If you are doing in Java, there is a datatype for very large no. but in C, you have to take the no. as string and do the addition of two no.s by writing a function for addition of two strings.

                • + 0 comments

                  use python or java big integer because double will not work

              • + 0 comments

                thanks buddy

          • + 2 comments

            i wrote it in c..its giving correct output in devcpp,but here it shows wrong output..

            #include<stdio.h>
            #include<string.h>
            void stringmul(char*,char*,char*);
            void stringadd(char*,char*,char*);
            void swap(char*,char*);
            void strdrev(char*);
            int main()
            {
            	char a[150],b[150];
            	char mul[150]="",add[150]="";
            	int l1,l2,i,l,n,j;
            	scanf("%s",a);
            	scanf("%s",b);
            	scanf("%d",&n);
            	for(i=2;i<n;i++)
            	{
            		memset(mul,'\0',150);
            		memset(add,'\0',150);
            	stringmul(b,b,mul);
            	stringadd(mul,a,add);
            	l1=strlen(mul);
            	//printf("a=%s b=%s mul=%s add=%s\n",a,b,mul,add);
            	for(j=0;j<l1;j++)
            	{
            		a[j]=b[j];
            		b[j]=add[j];
            	}
            	}
            printf("%s",add);
            	
            	
            	
            }
            void stringmul(char *a,char *b,char *mul)
            {
            	int i,j,l1,l2,c,c1,temp=0,k,temp1;
            		l1=strlen(a);
            	l2=strlen(b);
            	//printf("(%s,%s)",a,b);
            	strdrev(a);
            	//strdrev(b);
            	//printf("(%s,%s)",a,b);
            	for(i=0;i<l1;i++)
            	{
            		c=0;
            		k=0;
            		c1=0;
            		for(j=0;j<l2;j++)
            		{
            			
            			temp=(a[i]-'0')*(b[j]-'0')+c;
            			if(mul[i+j+k]==0)
            			temp1=(mul[i+j+k])+(temp%10)+c1;
            			else
            			temp1=(mul[i+j+k]-'0')+(temp%10)+c1;
            			mul[i+j+k]=(temp1%10)+'0';
            			c1=temp1/10;
            			c=temp/10;
            	
            			
            			
            		}
            	if(c1!=0||c!=0)
            	mul[i+j+k]=c1+c+'0';
            	k++;
            }
            strdrev(mul);
            	strdrev(a);
            }
            void stringadd(char *a,char *b,char *add)
            {
            	int i,l1,l2,c,temp=0,p,q;
            	l1=strlen(a);
            	l2=strlen(b);
            	strdrev(a);
            	strdrev(b);	
            	int l=l1>l2?l1:l2;
            	c=0;
            	for(i=0;i<l;i++)
            	{
            		temp=0;
            		if(i<l1)
            		temp=a[i]-'0';
            		if(i<l2)
            		temp=temp+b[i]-'0';
            		temp=temp+c;
            		add[i]=(temp%10)+'0';
            			c=temp/10;
            			
            			
            		}
            	if(c!=0)
            	add[i]=c+'0';
            strdrev(add);
            strdrev(a);
            strdrev(b);
            }
            void strdrev(char *a)
            {
            	int l=strlen(a),i=0;
            	l--;
            	while(i<l)
            	{
            		swap(&a[i],&a[l]);
            		i++;
            		l--;
            	}
            }
            void swap(char *a,char *b)
            {
            	char temp;
            	temp=*a;
            	*a=*b;
            	*b=temp;
            }
            
            • + 1 comment

              programing with the combination of codes and notes can always help. what is the meaning of the sentence like "a[i]-'0'"?

              • + 0 comments

                converting char a[i] to its decimal equivalent

            • + 1 comment

              same issue getting correct output in my IDE but segmentation fault while submittin... any suggestion?

              • + 0 comments

                Can you tell us which testcase is giving seg fault? You can just download that testcase and check yourself too. It must be an edge case or might be using enormous memory.

          • + 0 comments

            I get this awesome interesting and unique game which is online and you will love word unscrambler play by using special skills to win this Online Multiplayer game.

        • + 0 comments

          Very easy problem for python users.

          Hackerrank - Fibonacci Modified Solution

    • + 0 comments

      agreee

    • + 1 comment

      Although simple enough, I think it still uses the thoguht of DP - it keeps recording the two former numbers and build the solution from bottom to top, instead of recurring from top to bottom, which would lead to a huge number of unnecessary function calls.

      • + 2 comments

        Well you could do that, but you don't need to. I submitted a solution using dynamic programming, and one using just regular recursion. The difference in running time is so small that it prints the same running times, even though one runs in linear time and the other one in exponential time. They should increase the test size and limit the amount of running time so that without the use of dynamic programming you can't solve the problem imo.

        • + 3 comments

          This problem doesn't even need recursion.. a for loop can solve this problem too

          • + 1 comment

            Yes, BigInteger in for loop will solve it.

            • + 2 comments

              how u sloved big integer in for loop??can u explain?

              • + 2 comments

                Here is the snippet,

                    Scanner scn = new Scanner(System.in);
                    BigInteger t1 = new BigInteger(scn.nextInt()+"");
                    BigInteger t2 = new BigInteger(scn.nextInt()+"");
                    int n = scn.nextInt();
                
                    BigInteger temp = new BigInteger("0");
                    for(int i=3;i<=n;i++){
                        temp = t2;
                        t2 = t2.multiply(t2);
                        t2 = t2.add(t1);
                        t1 = temp;
                    }
                    System.out.println(t2);
                
                • + 1 comment

                  y is it necessary to add "" while initializing the constructor of biginteger ?

                  • + 2 comments

                    Because BigInteger doesn't take int in its constructor but can take a string .So adding "" makes a integer , string .

                    A nice way is to use valueOf() function of BigInteger class.

                    • + 0 comments

                      oh thank u

                    • + 0 comments

                      why not use:

                      scn.nextBigInteger();
                      

                      directly?

                • + 1 comment

                  my code was correct but how to use biginteger from your code i understands

                  • + 0 comments
                    • static String fibonacciModified(int t1, int t2, int n) { BigInteger c=new BigInteger("0"); BigInteger a=new BigInteger(t1+""); BigInteger b=new BigInteger(t2+""); for (int i=0;i { c=a.add(b.multiply(b)); a=b; b=c; } return c.toString(); }** I hope this will help you
              • + 2 comments
                public class Solution {
                
                    public static void main(String[] args) {
                        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
                        int i,n;
                        BigInteger a,b;
                        Scanner sc=new Scanner(System.in);
                        a =  sc.nextBigInteger();
                        b =  sc.nextBigInteger();
                        n = sc.nextInt();
                        BigInteger [] val = new BigInteger[n];
                        val[0] = a;
                        val[1] = b;
                        for(i=2;i<n;i++){
                            val[i]= (val[i-1].pow(2)).add(val[i-2]);
                        }
                        System.out.println(val[i-1]);
                    } 
                }
                
                • + 0 comments

                  thanks

                • + 0 comments

                  Compile time error

                  Compile Message

                  Solution.java:6: error: cannot find symbol BigInteger a,b; ^ symbol: class BigInteger location: class Solution Solution.java:7: error: cannot find symbol Scanner sc=new Scanner(System.in); ^ symbol: class Scanner location: class Solution Solution.java:7: error: cannot find symbol Scanner sc=new Scanner(System.in); ^ symbol: class Scanner location: class Solution Solution.java:11: error: cannot find symbol BigInteger [] val = new BigInteger[n]; ^ symbol: class BigInteger location: class Solution Solution.java:11: error: cannot find symbol BigInteger [] val = new BigInteger[n]; ^ symbol: class BigInteger location: class Solution 5 errors

          • + 2 comments

            I solved it with recursion. Probably stupid but the problem is defined recursively so it was the first thing that popped in my mind. If you memoize the recursive calls it needn´t be terribly inefficient.

            • + 1 comment

              Can you post your recursive solution, please.

              • + 1 comment
                public static BigInteger fiboMod(BigInteger t1,BigInteger t2,int n){
                        n = n-1;
                        if(n == 1){
                            return t2;
                        }
                        return fiboMod(t2,t2.pow(2).add(t1),n);
                    }
                • + 0 comments

                  This is not DP. Its plain Recursion.

            • + 1 comment

              The point of doing it in DP and not in recursion is that recursion takes a lot of time while DP doesnt. Doesnt make any sense doing it in recursion as it is said to do it in dp.

              • + 0 comments

                Yes, but memoized recursion can give similar results to DP with only slight overhead (e.g. here).

          • + 0 comments

            recurssion with memoziation is same as iterative

        • + 2 comments

          I did it using a simple loop and I don't even know what DP is. Could you please show me what a solution using DP looks like?

          function main() {
              let [a, b, n] = input.split(' ').map(Number);
              a = new BigNumber(a);
              b = new BigNumber(b);
              for (let i = 3; i <= n; i++) {
                  var c = next(a, b);
                  a = b, b = c;
              }
              process.stdout.write(c.toFixed());
          }
          
          • + 1 comment

            DP comes from Dynamic Programming, is an algorithm paradigm or a technique to solve complex problems breaking them into small ones. Just like you I still do not have any idea about what it is or how to implemented. If you find any DP course for dummies, please let me know, the ones I've found are a little bit difficult to follow.

            • + 0 comments

              https://www.youtube.com/watch?v=P8Xa2BitN3I Check this video out, it might be helpful if you want to understand the basics of Dynamic programming.

          • + 0 comments

            Your solution is a DP solution.

            You are calculating tn by solving the problem from t1 to tn, and recording the results in order to calculate the one you need.

            That's the whole idea of dynamic programming: to solve a complex instance of a problem using the solution to smaller instances.

            This problem is so simple that you can't really appreciate the technique. If you want an example of a more "serious" DP algorithm, you might look to a classic like the Wagner–Fischer algorithm to compute the distance between strings. It's simple enough but not trivial.

    • + 1 comment

      Yeah, Python makes this problem pretty trivial

      • + 1 comment

        True, I switched from JavaScript just to get it done.. did find a pitfall though.

        third = math.pow(second, 2) + first
        

        will produce weird numbers from the 8th iteration.

        instead must use: second*second + first

        • + 1 comment

          That's because math.pow() will use floating-point numbers. It is more typically used when the power is a real number, not (necessarily) an integer.

          To raise integers to an integer power, use the exponentiation operator **:

          third = second**2 + first
          

          (Of course to compute a square of x, x*x works just fine as well.)

    • + 3 comments

      can u pls explain how to handle big integer in c++.

      • + 1 comment

        AFAIK, there's no easy way to do this problem in C++ with the libraries provided. In real life you'd use a bignum library like GNU MP or Boost.Multiprecision, but those libraries aren't available here.

        You can certainly roll your own, but that seems a little extreme.

        I've done all the other algorithm problems in C++, but for this one I switched to Java so I could use java.math.BigInteger.

        • + 0 comments

          ohk.thank you

      • + 4 comments

        Here is how I do it. You can actually make it faster by playing with Base.

        #include <cmath>
        #include <cstdio>
        #include <vector>
        #include <iostream>
        #include <algorithm>
        using namespace std;
        
        namespace
        {
            char toChar(char d) {
                return d | 0x30;
            }
        }
        
        constexpr unsigned Base = 100;
        
        class BigNumber
        {
        private:
            string m_num;
        
        public:
            BigNumber(int num = 0);
            BigNumber(const BigNumber & other);
            BigNumber(BigNumber && other);
            BigNumber &operator+=(const BigNumber & num2);
            void swap(BigNumber &num);
        
            BigNumber &operator=(BigNumber num);
        
            friend BigNumber operator*(const BigNumber & num1, const BigNumber & num2);
            friend BigNumber operator+(BigNumber num1, const BigNumber & num2);
            friend ostream & operator<<(ostream & outstream, const BigNumber & num);
        
        private:
            void add(const BigNumber &num, int exp);
        };
        
        BigNumber::BigNumber(int num)
        {
            for (; num; num /= Base) {
                m_num.push_back(num % Base);
            }
            if (m_num.empty()) {
                m_num.push_back(0);
            }
        }
        
        BigNumber::BigNumber(const BigNumber & other)
            : m_num(other.m_num)
        { }
        
        BigNumber::BigNumber(BigNumber && other)
            : m_num(std::move(other.m_num))
        { }
        
        BigNumber operator*(const BigNumber & num1, const BigNumber & num2)
        {
            BigNumber precomp[Base];
            for (int i = 1; i < Base; ++i) {
                precomp[i] = precomp[i - 1] + num1;
            }
        
            BigNumber result;
            int exp = 0;
            for_each(num2.m_num.begin(), num2.m_num.end(), [&result, &precomp, &exp](char c) {
                result.add(precomp[c], exp++);
            });
            return result;
        }
        
        void BigNumber::add(const BigNumber & num, int exp)
        {
            if (exp > m_num.size()) {
                m_num.append(exp - m_num.size(), 0).append(num.m_num.begin(), num.m_num.end());
            } else {
                auto b1 = m_num.begin() + exp, e1 = m_num.end();
                auto b2 = num.m_num.begin(), e2 = num.m_num.end();
        
                int r = 0;
                for (; b1 != e1 && b2 != e2; ++b1, ++b2, r/= Base) {
                    r += *b1 + *b2;
                    *b1 = r % Base;
                }
        
                for (; r && b1 != e1; ++b1, r /= Base) {
                    r += *b1;
                    *b1 = r % Base;
                }
        
                for (; r && b2 != e2; ++b2, r /= Base) {
                    r += *b2;
                    m_num.push_back(r % Base);
                }
        
                if (b2 != e2) {
                    m_num.append(b2, e2);
                }
        
                if (r) {
                    m_num.push_back(r);
                }
            }
        }
        
        BigNumber &BigNumber::operator+=(const BigNumber & num2)
        {
            add(num2, 0);
            return *this;
        }
        
        BigNumber operator+(BigNumber num1, const BigNumber & num2)
        {
            num1.add(num2, 0);
            return num1;
        }
        
        ostream & operator<<(ostream & outstream, const BigNumber & num)
        {
            string x(num.m_num.size() * 2, 0);
            for (int i = 0; i < num.m_num.size(); ++i) {
                auto d = num.m_num[i];
                x[2 * i] = toChar(d % 10);
                x[2 * i + 1] = toChar(d / 10);
            }
            if (x.back() == '0') {
                x.erase(x.size() - 1);
            }
            reverse(x.begin(), x.end());
            return outstream << x;
        }
        
        BigNumber & BigNumber::operator=(BigNumber num) {
            m_num = std::move(num.m_num);
            return *this;
        }
        
        void BigNumber::swap(BigNumber & num)
        {
            m_num.swap(num.m_num);
        }
        
        int main() {
            int _a, _b, n;
            cin >> _a >> _b >> n;
        
            BigNumber a(_a), b(_b);
            while (n-- > 2) {
                a += b * b;
                a.swap(b);
            }
        
            cout << b;
            return 0;
        }
        
        • + 0 comments

          well done man

        • + 1 comment

          Please can you explain your code

          • + 0 comments

            I'm sorry, I got lost in the conversation, which code?

        • [deleted]
          + 1 comment

          you are awesome man

          • + 0 comments

            include

            include

            include

            include

            int main() { int i=2,x,y,n; int z,a[100]={0}; scanf("%d %d %d",&x,&y,&n);

            while(i<n)
            

            { z=0; z=x+pow(y,2); x=y; y=z; i++; a[z]+=z; }
            printf("%d",a[z]); return 0; }

            this my code it is displaying segementation error can anyone help me in getting the actual bug in this code

        • + 0 comments

          I barely know a thing or two about that ostream operator,great work man!!

      • + 4 comments

        I passed all tests by using the Karatsuba multiplication algorithm with my own Big Integer implementation. Very dumb by the way, but fast enough to find the 24 modified Fibonacci number in a half of second (0 1 24). Nothing special work was done about working with number representation – store it as is in a base 10 in a vector. If it is still relevant for you, email me (taenaru@gmail.com) and I'll gladly explain you how it might work.

        • + 0 comments

          can you send me explaination

          nickholden786@gmail.com

        • + 0 comments

          It's a waste of dev time, imho. Karatsuba algo replaces 2mul+1add with 1mul+4add. They say mul takes 3-4 times cycles of add these days, so you gonna get max 12.5% speed up (or zero, if it's actually 3 times) for the code which probably takes less than 20% of execution time (memory access will be the bottleneck, not number crunching)

        • + 2 comments

          No need for that young fella 🧐

          JAVA SOLUTION

          100% TEST CASES ✅

          COMPLEXITY IN 0(N) TIME

              static String fibonacciModified(int t1, int t2, int n) {
                  BigInteger[] arr = new BigInteger[n];
                  BigInteger tOne = new BigInteger(Integer.toString(t1));
                  BigInteger tTwo = new BigInteger(Integer.toString(t2));
                  arr[0] = tOne;
                  arr[1] = tTwo;
                  for(int i = 2; i < n; i++){
                      BigInteger iMinus1BigInteger = arr[i - 1];
                      BigInteger iMinus2BigInteger = arr[i - 2];
                      BigInteger powered = iMinus1BigInteger.pow(2);
                      BigInteger poweredAndSum = powered.add(iMinus2BigInteger);
                      arr[i] = poweredAndSum;
                  }
                  BigInteger result = arr[n-1];
                  return result.toString();
              }
          
          • + 0 comments

            but we have to return int value not string, so how we can do that

          • + 0 comments

            ''' static BigInteger fibonacciModified(int t1, int t2, int n) { BigInteger[] arr = new BigInteger[n]; BigInteger tOne = new BigInteger(Integer.toString(t1)); BigInteger tTwo = new BigInteger(Integer.toString(t2)); arr[0] = tOne; arr[1] = tTwo; for(int i = 2; i < n; i++){ BigInteger iMinus1BigInteger = arr[i - 1]; BigInteger iMinus2BigInteger = arr[i - 2]; BigInteger powered = iMinus1BigInteger.pow(2); BigInteger poweredAndSum = powered.add(iMinus2BigInteger); arr[i] = poweredAndSum; }''' BigInteger result = arr[n-1];

                return result;
            
            }
            
    • + 1 comment

      what is the function that is to be used in c to handle such big integer like this 84266613096281243382112? help me in doing this

      • + 0 comments

        There is not! And this is the challenge. You will need to cut the number in pieces to work with it.

    • + 0 comments

      Same concern. Luckily I'm on Python.

    • + 0 comments

      Totally agree. This really shouldn't be categorized as a dynamic programming problem. Without having to worry about big numbers the solution is trival.

      For people using C#, just use System.Numerics.BigInteger.

    • + 0 comments

      Tried doing it with strings. But, it TLE'd on 4 test cases! T_T

      #include<bits/stdc++.h>
      using namespace std;
      #define ll long long
      #define PI 3.1415926535897932384626
      #define pb push_back
      #define mp make_pair
      #define F first
      #define S second
      #define br '\n'
      #define FOR(i, a, b) for(int i=int(a);i<=int(b);++i)
      #define FORR(i, a, b) for(int i=int(a);i>=int(b);--i)
      #define TR(it, x) for(auto it = x.begin(); it != x.end(); it++)
      #define TRR(it, x) for(auto it = x.rbegin(); it != x.rend(); it++)
      #define deb(x) cout<<#x<<"-"<<x<<"\n"
      typedef pair<int, int> pii;
      typedef pair<float, float> pff;
      typedef vector<int> vi;
      typedef vector<float> vf;
      typedef vector<pii> vpii;
      typedef vector<vi> vvi; 
      typedef stack<int> si;
      typedef queue<int> qi;
      mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
      const int mod = 1e7;
      const int MAX = 1e8;
      
      /* ========== START HERE ========= */
      string multiply(string num1, string num2){
          int n1 = num1.size();
          int n2 = num2.size();
          if (n1 == 0 || n2 == 0)
              return "0";
          vector<int> result(n1 + n2, 0);
          int i_n1 = 0;
          int i_n2 = 0;
          for (int i = n1 - 1; i>=0; i--) {
              int carry = 0;
              int n1 = num1[i] - '0';
              i_n2 = 0;
              FORR(j,n2 - 1,0) {
                  int n2 = num2[j] - '0';
                  int sum = n1 * n2 + result[i_n1 + i_n2] + carry;
                  carry = sum / 10;
                  result[i_n1 + i_n2] = sum % 10;
       
                  i_n2++;
              }
              if (carry > 0)
                  result[i_n1 + i_n2] += carry;
              i_n1++;
          }
          int i = result.size() - 1;
          while (i >= 0 && result[i] == 0)
              i--;
          if (i == -1)
              return "0";
          string s = "";
             
          while (i >= 0)
              s += std::to_string(result[i--]);
       
          return s;
      }
      
      string findSum(string str1, string str2){
          if (str1.length() > str2.length())
              swap(str1, str2);
          string str = "";
          int n1 = str1.length(), n2 = str2.length();
          reverse(str1.begin(), str1.end());
          reverse(str2.begin(), str2.end());
       
          int carry = 0;
          for (int i=0; i<n1; i++){
              int sum = ((str1[i]-'0')+(str2[i]-'0')+carry);
              str.push_back(sum%10 + '0');
              carry = sum/10;
          }
          FOR(i,n1,n2-1){
              int sum = ((str2[i]-'0')+carry);
              str.push_back(sum%10 + '0');
              carry = sum/10;
          }
          if (carry)
              str.push_back(carry+'0');
          reverse(str.begin(), str.end());
          return str;
      }
      
      string fibonacci_modified(string t1,string t2,int n){
          string dp[n+1];
          dp[1]=t1;
          dp[2]=t2;
          FOR(i,3,n){
              dp[i]=findSum(multiply(dp[i-1],dp[i-1]),dp[i-2]);
          }
          return dp[n];
      }
      
      
      void solve() {
          string t1,t2;
          int n;
          cin>>t1>>t2>>n;
          cout<<fibonacci_modified(t1,t2,n);
      }
      
      /* ========== THE MAIN ========= */
      
      int main() {
          ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
          srand(chrono::high_resolution_clock::now().time_since_epoch().count());
          int t=1;
          //scanf("%d",&t);
          while(t--){
              solve();
          }
          return EXIT_SUCCESS;
      }