斐波那契数列

递归得到斐波那契数列第n项

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        System.out.println(fib(5));
    }
    
    public static int fib(int n)
    {
        if(n == 1) return 0;
        if(n == 2) return 1;
        return fib(n - 1) + fib(n - 2);
    }
}

非递归,用数组得到斐波那契数列的前n项

import java.util.*;
public class Main
{
    static int N = 50;
    static int n;
    static int[] a = new int[N];
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        a[0] = 0;
        a[1] = 1;
        for(int i = 2;i < n;i ++)
        {
            a[i] = a[i - 1] + a[i - 2];
        }
        for(int i = 0;i < n;i ++)
        {
            System.out.print(a[i] + " ");
        }
        
    }
}

非递归优化版得到斐波那契数列

import java.util.*;
public class Main
{
    static int n;
    public static void main(String[] args){
        int a = 0;
        int b = 1;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        for(int i = 1;i <= n;i++){
            System.out.print(a + " ");
            int fn = a + b;
            a = b;
            b = fn;
            
        }
        
    }
}

你可能感兴趣的:(算法,java,算法,开发语言)