(java)三种方法求斐波那契数列的第n项

Java使用三种方式实现斐波那契数列求解 阅读详情

题目:写一个函数,输入n,求斐波那契数列的第n项。斐波那契数列的定义如下:

解答本题的方法有三:

  • 按照定义编程,使用的方法是递归。
  • 方法一递归分解的子问题存在大量的重复计算,于是我们将递归改为自上而下的循环实现。(本题的核心)
  • 采用数学公式实现。

分析:

使用递归会有许多的重复计算:

 方法三涉及到的数学公式:

代码实现如下: 

package com.example.offer;

/**
 *          0  n=0
 * f(n)=    1  n=1
 *          f(n-1)+f(n-2)  n>1
 */
public class FibonacciTest {

    public static void main(String[] args) {
       for (int i = 0; i < 10; i++) {
            System.out.println("方法一:"+fibonacci01(i));
            System.out.println("方法二:"+fibonacci02(i));
            System.out.println("方法三:"+fibonacci03(i));
        }
    }
    /**
     *  简单的实现  递归的实现存在很多的重复计算
     * @param n 求第n个斐波那锲数
     * @return
     */
    public static long fibonacci01(long n){
        if(n<=0){
            return 0;
        }
        if(n==1){
            return 1;
        }
        return fibonacci01(n-1)+ fibonacci01(n-2);
    }

    /**
     *  将递归的实现转为循环  时间复杂度为O(n)
     * @param n 求第n个斐波那锲数
     * @return
     */
    public static long fibonacci02(long n) {
        if(n<=0){
            return 0;
        }
        if(n==1){
            return 1;
        }
        long fibNMinusOne=1;//n-1
        long fibNMInusTwo=0;//n-2
        long fibN=0;
        for (int i = 2; i <= n; i++) {
            fibN=fibNMinusOne+fibNMInusTwo;

            fibNMInusTwo=fibNMinusOne;
            fibNMinusOne=fibN;
        }
        return fibN;
    }

    /**
     * 采用数学公式
     * --                 --            --      -- (n-1)
     * \   f(n)   f(n-1) \      =     \  1  1  \
     * \   f(n-1)   f(n+1) \            \  1  0  \
     * --                  --           --      --
     * 由此可知,我们只需要计算后面矩阵的值 即可以知道 f(n)的值
     * @return
     */
    public static long fibonacci03(int n){
        int[] result={0,1};
        if(n<2){
            return result[n];
        }
        //当大于2的情况
        Matrix2By2 powerNMinus2=matrixPower(n-1);
        return powerNMinus2.m_00;
    }

    /**
     * 计算矩阵Matrix2By2(1,1,1,0)的n次方
     * @param n
     * @return
     */
    public static Matrix2By2 matrixPower(long n){
        //分三种情况 n=1;n为偶数;n为奇数
        Matrix2By2 matrix=null;
        if(n==1){ //n为1
            matrix=new Matrix2By2(1,1,1,0);
        }else if(n%2==0){ //n为偶数
            matrix=matrixPower(n/2);
            matrix=matrixMultiply(matrix,matrix);
        }else if(n%2==1){//n为奇数
            matrix=matrixPower((n-1)/2);
            matrix=matrixMultiply(matrix,matrix);
            matrix=matrixMultiply(matrix,new Matrix2By2(1,1,1,0));
        }
        return matrix;
    }

    /**
     * 两个矩阵相乘
     * @return
     */
    public static Matrix2By2 matrixMultiply(Matrix2By2 matrix1,Matrix2By2 matrix2){
        return new Matrix2By2(
                matrix1.m_00*matrix2.m_00+matrix1.m_01*matrix2.m_10,
                matrix1.m_00*matrix2.m_01+matrix1.m_01*matrix2.m_11,
                matrix1.m_10*matrix2.m_00+matrix1.m_11*matrix2.m_10,
                matrix1.m_10*matrix2.m_01+matrix1.m_11*matrix2.m_11
        );
    }
}

/**
 *  2*2的矩阵
 */
class Matrix2By2{
    //一个2*2的矩阵 有4个元素
    public long m_00;
    public long m_01;
    public long m_10;
    public long m_11;

    public Matrix2By2(){

    }
    public Matrix2By2(long m_00,long m_01,long m_10,long m_11){
        this.m_00=m_00;
        this.m_01=m_01;
        this.m_10=m_10;
        this.m_11=m_11;
    }
}

时间复杂度分析:方法一计算量随着n的增大急剧增大,时间复杂度是以n的指数递增,时间复杂度为O(2^n);方法二采用自上而下的循环,时间复杂度为O(n),性能比方法一大大优化,是此题的核心解法;第三种方法使用数学函数,时间复杂度为O(logn)。但是代码比较复杂,时间常数较大,此方法做了解即可,软件中使用较少。

三种方法求斐波那契数列的第n项--java 目录 斐波那契数列的定义 代码实现: 1、递归 2、循环 3、迭代 思想: 斐波那契数列的定义 上图是百度对于斐波那契数列的定义。 总的来说:这个数列从第3项开始,每一项都等于前两项之和。 代码实现: 1、递归 相信大家对于递归都不陌生了,递归就是一个程序调用自身的编程技巧。 这里第一种方法就采用递归的形式来解决这个问题。 下面上代码: 程序运行截图: 但是用递归方法解决这个问题存在一个问题就是当你要求的数字较大时,函数调用可能会造成栈溢出的错误。 就是.. 阅读详情

相关推荐

计算斐波那契数列的第n项

斐波那契数列的第 n 项定义如下:F(0) = 0,F(1) = 1,F(n) = F(n-1) + F(n-2),其中 n > 1,n 是正整数。编写一个函数,计算斐波那契数列的第 n 项。 下面是一个Java函数,用于计算斐波那契数列的第n项:

m0_47946173的博客 1307

Java求斐波那契数列第n项详解

求斐波那契数列的第n项,用迭代(循环)实现。

小只.的博客 2887

java求数列:1、1、2、3、5、8、13、21、34、……前N项和。

求数列:1、1、2、3、5、8、13、21、34、……前N项和。 import java.util.Scanner; public class countTotalN { public static int Fibonacci(int n) { int f1 = 1; int f2 = 1; int bef = f1; int aft = f2; int fn = 0; ...

梦里逆天的博客 3900

Java获取第n个斐波那契数

前提基准: f(0)=0; // 第0个斐波那契数是0 f(1)=1; // 第1个斐波那契数是1 f(2)=1; // f(2)=f(1)+f(0) // 第2个斐波那契数是1 /** * 获取第n个斐波那契数 * @param n * @return */ private static int getFibo(int n) { if(n == 0) return 0; if(n == 1 || n =

Jerry的博客 616

计算斐波那契数列第n项值的方法

public class Demo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); System.out.println(f(n)); } public static long f(int n){ Scanner sc

ja123y的博客 2802

MATLAB实战:从零推导合成孔径雷达(SAR)后向投影(BP)算法核心公式与代码实现

本文详细介绍了如何使用MATLAB从零推导合成孔径雷达(SAR)后向投影(BP)算法的核心公式与代码实现。通过基础概念讲解、数学原理推导、距离维脉冲压缩实现及完整MATLAB代码展示,帮助读者掌握SAR成像的关键技术。特别针对BP算法的优化技巧和常见问题提供了实用解决方案,适合雷达信号处理领域的开发者和研究者参考。

weixin_28683689的博客 251

利用Python求斐波那契数列的第N项以及前N项和(循环、递归、集合)

著名的斐波那契数列,即从第三项开始,每一项都等于前两项之和。 之前写过利用Java语言来编写,由于最近正在学Python,所以将自己的想法记录在此,有需要的朋友可以参考一下。 写在前面:这里的三个方法其实思路是差不多的,因为第一项和第二项没有前两项,所以无法直接求出本项,故使用了直接指定的方式。 方法一:利用if判断和for循环来实现 这个方法感觉稍微有些复杂,使用到了if判断、for循环以及变量交换等知识点,难度不高,初学者理解起来可能稍微有些困难(不推荐使用次方法,没啥技术含量,完全是为了用for循环实

编程小陈 5万+

保姆级教程:用达芬奇Configurator配置CAN总线(从DBC导入到Controller设置)

本文详细介绍了使用达芬奇Configurator工具从DBC文件导入到CAN总线控制器设置的全流程配置方法。通过环境准备、CAN控制器模式选择、硬件参数配置、通信参数优化及通信栈集成等关键步骤,帮助开发者高效完成AUTOSAR架构下的CAN总线开发,特别适合汽车电子领域的工程师参考。

weixin_30529023的博客 440

Java——斐波那契数列的第n项与前n项和

下面是从网上找的一张关于斐波那契的图片,该图片解释了什么是斐波那契 序列 注意:第0项值为0 第1项值为1 第2项值为1 之后每一项都等于其前两项的和 求斐波那契额的第n项的值 方法一: static int fib(int n) { //当n为0或1时,结果为其本身 return (2>n) ? n: fib(n-1)+fib(n-2); } 方法二: publi...

笔记 4719

算法面试准备 - 手撕系列第五期 - 单头注意力机制(包括Self_atten和Cross_atten)

算法面试准备 - 手撕系列第五期 - 单头注意力机制(包括Self_atten和Cross_atten)

m0_62030579的博客 3606

ray.tune调参学习笔记0:调参基本流程

本篇总结python中使用tune调参的整体流程

Mr_111000的专栏 2621

写一个函数,输入n,求斐波那契(Fibonacci) 数列的第n项

* 写一个函数,输入n,求斐波那契(Fibonacci) 数列的第n项 * @param n Fibonacci数的项数 * @return 第n项的结果 在数学上,费波那契数列是以递归的方法来定义: (n≧2) public static long fibonacci(int n) { // 当输入非正整数的时候返回0 if (n <= 0...

cccfire的博客 1万+

Stata新手避坑:用reghdfe搞定行业、地区多重固定效应,告别‘共线性’报错

本文详细介绍了如何使用Stata中的reghdfe命令高效处理多重固定效应问题,解决传统方法在面板回归中遇到的共线性报错和低R²问题。通过实战案例和高级技巧,帮助新手快速掌握行业、地区等多维固定效应的控制方法,提升经济学和金融学研究的分析效率。

weixin_30635053的博客 419

求斐波那契数列的第n项 java

写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下: F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 1 < N <= 100. 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 后一项 = 前一项+前前一项 首先我们会想到使用递归: public int f

Cangwuwuwu 3243

中兴问天 BE7200MAX SFP 光口用华为猫棒替代光猫完整配置教程

PPPoE 账号密码:若原光猫为 Route 模式,在宽带设置页可见用户名,密码需按 F12 打开浏览器开发者模式,点击密码输入框,查看代码中 “value=” 后的内容即为明文密码。若仍失败,核对 PON 类型是否与运营商网络匹配。PON 认证信息:LOID(逻辑 ID,部分地区含密码)、设备 SN 码(标签或设备信息页)、PON 类型(GPON/EPON,运营商网络类型)。电脑保持与路由器连接,访问路由器管理地址(默认通常为 192.168.5.1,可参考路由器说明书),登录后台。

Gulper_Eel的博客 3319

[EdgeAI] NXP eIQ 机器学习Toolkit (一):准备篇

eIQ™机器学习(ML)软件开发环境支持在恩智浦EdgeVerse™微控制器和微处理器(包括i.MX RT跨界MCU和i.MX系列应用处理器)上使用ML算法。eIQ ML软件包括称为eIQ Toolkit的ML工作流工具以及推理引擎、神经网络编译器和优化库。............

HowieXue 薛永浩的博客 1万+

求斐波那契数列的第N项 (迭代和递归)

求斐波那契数列的第N项 (迭代和递归)

yk199905232994的博客 5528

华为OD机试真题 新系统【小学英语老师批改作文】

华为OD机试 新系统真题【小学英语老师批改作文】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【小学英语老师批改作文】

qq_45776114的博客 922

求斐波那契数列得第N项(Java实现)

1. 问题描述 写一个函数,输入n,求斐波那契(Fibonacci)数列的第n项(即F(N))

weixin_37987845的博客 6800

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

使用递归方法,求斐波那契数列的前n项

使用递归方法,求斐波那契数列的前n项 关注 关注 关注 package 两个题3_17; import java.util.Scanner; public class Main { /* 许昌学院 */ public static void main(String[] args) { Scanner scanne...

mzy1711231996的博客 5951

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

java求斐波那契前n项和_算法之斐波那契数列如何求第n个值与前n项和?(Java)...

斐波那契数列指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波纳契数列以如下被以递推的方法定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3,n∈N*)。1.题目1.1.求斐波那契数列的第n项的值2.2.求斐波那契数列前n项的和2.例子2.1.求第n项的值输入:6输出:82.2.求前n项的和输入:6输出:203.解析3.1.求第n...

weixin_32487557的博客 4592

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

详解java递归求解斐波那契数列第n项

文章目录问题一、什么是斐波那契数列?二、解题思路三、实战代码后记 问题 求斐波那契数列的第n项。(迭代实现) 提示:以下是本篇文章正文内容,下面案例可供参考 一、什么是斐波那契数列? 斐波那契数列(Fibonacci sequence),又称黄金分割数列,因数学家莱昂纳多·斐波那契(Leonardo Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……在数学上,斐波那契数列以如下被以递推的方法定义: F(0)=0,F(.

m0_57180439的博客 5234

Java 递归算法之斐波那契数列第 N 项

斐波那契数列(Fibonacci sequence),也称之为黄金分割数列,由意大利数学家列昂纳多・斐波那契(Leonardo Fibonacci)提出。斐波那契数列指的是这样的一个数列:1、1、2、3、5、8、13、21、34、……,这个数列从第 3 项开始,每一项都等于前面两项之和。在数学上,斐波那契数列可以被递推的方法定义如下: F(1)=1,F(2)=1,F(n)=F(n – 1)+F(n – 2)(n≥ 3,n∈ N*) 1.斐波那契数列的递归终止条件 显然易见,通过观察斐波那契数列的定...

爱干饭的猿的博客 2895

【Java练习】求斐波那契数列的第n项

学习目标: 目标:快速掌握 Java 入门知识 学习内容: 本文内容:使用java语言:求斐波那契数列的第n项 斐波那契数列介绍: 斐波那契数列(Fibonacci sequence),又称黄金分割数列、因数学家莱昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波那契数列以如下被以递推的方法定义:F(0)=1,F(1)=1, F(n)=F(n - 1)+F(n - 2

zhangxxin的博客 2474

用for循环输出斐波那契数列并求前N项之和

原题如下:   求斐波那契数列前n项的和值,斐波那契数列如下:        1,1,2,3,5,8,13,21…… 前两位数是1,从第三位开始每位数都是前两位数之和。 import java.util.Scanner; public class FibNumber { public static void main(String[] args)...

挥舞地带 6591

【Java】输出n项斐波那契数列

import java.util.Scanner; public class 递归 { //求第n个斐波那契数 static int fabnaci(int n) { if(n==0)return 0; if(n==1)return 1; return fabnaci(n-1)+fabnaci(n-2); } public static void main(String[] a...

Bry'ce的博客 3707
上一篇: java:用两个队列实现栈
下一篇: 剑指offer(java)——在递增旋转数组中查找最小值
程序员楂楂
博客等级 码龄9年 17粉丝 70原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值