Search code examples
javadynamic-programmingfibonaccigreatest-common-divisor

Large Fibonacci with GCD


I got this question in a programming challenge a few days before.

enter image description here

enter image description here

I got only one test case passed out of 20 at the back-end. This is my solution

import java.util.Scanner;
class TestClass {
    public static void main(String args[] ) throws Exception {
        Scanner s = new Scanner(System.in);
        int size = s.nextInt();
        int[] input = new int[size];


        long[] fiboDp = new long[1000000];
        fiboDp[0] = 0;
        fiboDp[1] = 1;

        for(int index = 2;index<1000000;++index) {
            fiboDp[index] = (fiboDp[index-1]%1000000007+fiboDp[index-2]%1000000007)%1000000007;

        }

        int query = s.nextInt();

        for(int index = 0; index < size; ++index) {
           input[index] = s.nextInt();
        }

        long[][] dpans = new long[size][size];

        for(int i = 0; i < size; ++i) {
            long gcdAns = fiboDp[input[i]];

            for(int j = i; j < size;++j) {
                if(i == j) {
                   dpans[i][j] = gcdAns; 
                }
                else {
                    dpans[i][j] = gcd(dpans[i][j-1],fiboDp[input[j]]);
                }
            }
        }

        while(query > 0) {
            int left = s.nextInt();
            left = left-1;
            int right = s.nextInt();
            right = right-1;

          //  long ansGCD = fiboDp[input[left]];
          //  for(int index =left ; index<= right;++index) {
          //      ansGCD = gcd(ansGCD,fiboDp[input[index]]);
          //  }
            System.out.println(dpans[left][right]);
            query--;
        }
    }

    static long gcd(long a, long b) {
        return b == 0? a : gcd(b,a%b);
    }

}

I think I know why my code is wrong because array's element size is 10^9 Fibonacci array size can be up to 10^6. And whenever I am accessing the larger index the array out of bound exception will occur. But I don't know how to resolve this. Is there any other approach?


Solution

  • Questions with range queries are usually solved with segment trees.
    It's a good and basic data-structure to start with competitive programming.

    Now, I would like to state one good property, viz.
    GCD( Fibo(a[l]), Fibo(a[l + 1]), ... , Fibo(a[r]) ) = Fibo( GCD(a[l], a[l + 1], ... , a[r]) ).

    Pre-requiste:
    1. Finding GCD of a range using segment tree => GeeksForGeeks
    2. Finding fibonacci fast in O(log n).

    My code in C++ with all passed cases : HackerEarth