具有GCD的大型斐波那契

时间:2017-07-16 05:47:18

标签: java dynamic-programming fibonacci greatest-common-divisor

我在几天前的编程挑战中得到了这个问题。

enter image description here

enter image description here

我只有一个测试用例在后端传递了20个。这是我的解决方案

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);
    }

}

我想我知道为什么我的代码错了,因为数组的元素大小是10 ^ 9斐波那契数组大小可以达到10 ^ 6。每当我访问较大的索引时,都会发生数组超出绑定的异常。但我不知道如何解决这个问题。还有其他方法吗?

1 个答案:

答案 0 :(得分:2)

范围查询的问题通常通过分段树来解决。
从竞争性编程开始,这是一个良好的基础数据结构。

现在,我想陈述一个好的财产,即。
GCD(Fibo(a [l]),Fibo(a [l + 1]),...,Fibo(a [r]))= Fibo(GCD(a [1],a [l + 1] ,. ..,[r]))。

预先要求:
1.使用分段树查找范围的GCD =&gt; GeeksForGeeks
2.在O(log n)中快速找到斐波纳契。

我在C ++中的代码包含所有已通过的案例:HackerEarth

相关问题