正确使用 long 原始数据类型及其数组

Correct usage of long primitive datatype and its array

我一直在编写一个问题,该问题要求我 code a modified version of fibonacci.
虽然现在代码已准备就绪,但它无法正常工作,因为返回的是 int 而不是 long

当以下内容用作输入时:0 1 10 输出是 -9223372036854775807 而不是这个 84266613096281243382112

代码如下:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static long arr[];

    public static long func(int n,long t1, long t2){
    arr = new long[n+1];
    arr[1]=t1;
    arr[2]=t2;
    return func(arr,n);    

    }
    public static long func(long[] arr, int n){
        if(n==0||n==1||n==2){
            return arr[n];
        }
        if(arr[n]!=0){
            return arr[n];
        }
        arr[n]=(long)(Math.pow(func(arr,n-1),2)+func(arr,n-2));
        return arr[n];
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        long t1= s.nextLong();
        long t2=s.nextLong();
        int n=s.nextInt();
        System.out.print(func(n,t1,t2));
    }
}


我不是在寻求逻辑方面的帮助,也不是在解决问题。我想知道我哪里出错了,即使我使用的是 long 数组,返回的答案仍然是 int

此外,任何有关如何处理长数组的帮助都会很棒。

返回的答案是 not integer,因为整数的最大值为 2147483647,如果值大于 integer,则返回 [-2147483647, 2147483647] 之间的数值。我觉得逻辑有问题

对于所有疑惑的人,我昨天意识到 long 的范围已经用尽,因此无法用于解决问题。我已经使用了 BigInteger class,并且有效。

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


    public static BigInteger func(int n,BigInteger t1, BigInteger t2){
    BigInteger arr[] = new BigInteger[n+1];
    arr[1]=t1;
    arr[2]=t2;
    return func(arr,n);    

    }
    public static BigInteger func(BigInteger[] arr, int n){
        if(n==0||n==1||n==2){
            return arr[n];
        }
        if(arr[n]!=null){
            return arr[n];
        }
        arr[n]=(func(arr,n-1).pow(2)).add(func(arr,n-2));
        return arr[n];
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        BigInteger t1= s.nextBigInteger();       
        BigInteger t2= s.nextBigInteger();       
        int n=s.nextInt();
        System.out.print(func(n,t1,t2));
    }
}

您可以改用此代码,因为他们不要求整个数组,而只要求第 n 个项。

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String args[] ) throws Exception {
        Scanner in=new Scanner(System.in);
        BigInteger t1=in.nextBigInteger();
        BigInteger t2=in.nextBigInteger();
        int n=in.nextInt();
        for(int i=0;i<n-2;i++)
        {
            BigInteger temp;
            temp = (t2.pow(2)).add(t1);
            t1=t2;
            t2=temp;
        } 
        System.out.println(t2);
    }
}