斐波那契数列1, 1 ,1, 3, 5, 9, 17, 31, ...找规律,用Java实现第n项数组

废话不多说直接上代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @create: 2019/03/30 14:56
 */
public class ArrTest {

    public static double[] tribonacci(double[] s, int n) {
        double[] arr=s;
        List<Double> list=new ArrayList<>();
        for(int i=0;i<arr.length;i++){
            list.add(Double.valueOf(arr[i]));
        }
        n=n-1;
        if(n>=3){
            for(int i=0;i<=n-3;i++){
                list.add(getNum(n,list));
                List<Double> newList=new ArrayList<>();
                newList.addAll(list.subList(list.size()-3,list.size()));
            }
        }
        double[] d=new double[n+1];
        for(int i=0;i<list.size();i++){
            d[i]=list.get(i);
        }
        return d;
    }

    public static Double getNum(int n,List<Double> list){
        Double sum=0.0;
        for(int i=list.size()-3;i<list.size();i++){
            Double  num=list.get(i);
            sum=num+sum;
        }
        return sum;
    }

    public static void main(String[] args) {
        double[] arr={1,1,1};
        System.out.println(Arrays.toString(tribonacci(arr,10)));
    }
}

注意:这里n>=3开始,原始数组为double[] arr={1,1,1};,后续我会优化一下,大家先凑合着用。

猜你喜欢

转载自blog.csdn.net/weixin_43969830/article/details/88941171