斐波那契数列第n项

1.求第n项(前77项)

import java.util.Scanner;

public class Main{
	public static void main(String[] args){
	    Scanner sc = new Scanner(System.in);
		
	    int n = sc.nextInt();
	    int a = 1, b = 1, i = 1;
	    while (i < n){
	        int c = a + b;
	        a = b;
	        b = c;
	        i ++;
	    }
		
	    System.out.println(a);
	}
}

2.求第n项(前76项)

import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        int[] f = new int[n + 1];
        f[0] = 0;
        f[1] = 1;
        for (int i = 2; i <= n; i ++)
            f[i] = f[i - 1] + f[i - 2];
            
        System.out.println(f[n]);
    }
}

3.求前n项

import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        int a = 0, b = 1;
        for (int i = 0; i < n; i ++){
            System.out.printf("%d ", a);
            int c = a + b;
            a = b;
            b = c;
        }
    }
}

2023-05-01 13:08:10 星期一
2023-05-01 17:15:28 星期一

posted on 2023-05-01 13:09  逆袭怪  阅读(6)  评论(0编辑  收藏  举报