【问题标题】:Large Fibonacci with GCD带有 GCD 的大斐波那契
【发布时间】:2017-07-16 05:47:17
【问题描述】:

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

在后端的 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 年前注册了帐户,但我通常不知道在哪里问这些问题。 meta.stackexchange.com/questions/129598/…。在这里我读过,我认为这是一个合适的地方问。如果没有,请指导我在哪里问。谢谢
  • 所以 Stack Overflow 是针对关于实际代码的特定问题。你的问题太笼统了。我建议,特别是考虑到这是一个编程挑战,你可以花一些时间在调试器中,并将你的问题缩小到一个不超过 10 行的代码块。
  • 好吧,我已经在比赛中解决了这个问题,这里是submission的链接。您应该注意的几个概念是GCD of fibonnaci numbersGCDs of given index ranges in an arrayO(log n) 复杂性中使用段树,在O(log n) 中使用第n 个斐波那契数Fast Doubling。 1/2
  • @SanketMakani,非常感谢。我不知道分段树,但我今天会自己学习。

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


【解决方案1】:

范围查询的问题通常用段树来解决。
这是从竞争性编程开始的良好且基本的数据结构。

现在,我想说明一个好的属性,即。
GCD( 斐波那契(a[l]), 斐波那契(a[l + 1]), ... , 斐波那契(a[r]) ) = 斐波那契( GCD(a[l], a[l + 1], . .. , a[r]) )。

先决条件:
1. 使用segment tree查找范围的GCD => GeeksForGeeks
2. 在 O(log n) 内快速找到斐波那契。

我的 C++ 代码以及所有通过的案例:HackerEarth

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 2019-12-19
    • 2012-12-29
    • 1970-01-01
    • 2014-03-21
    • 2011-03-24
    • 1970-01-01
    相关资源
    最近更新 更多