菲波那契数列是指这样的数列:数列的第一个和第二个数都为1,接下来每个数都等于前面2个数之和。给出一个正整数K,要求菲波那契数列中第k个数是多少。
下面是我的代码: k=input('');%matlab(Octave)的代码,读入控制台的数据,(这个地方我整了大概2天,因为matlab中很少用到这种方式) a=1; b=1; c=0; i=1; if k<=2 fprintf('%d',a); end while i<k-1 c=a+b; a=b; b=c; i=i+1; end fprintf('%d',c);%这个地方的输出是为了和题目的要求一样,用disp输出的话会有格式错误,如果用disp和sprintf同时使用可以
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void async function () { // Write your code here while(line = await readline()){ function fib(n){ if(n<3){ return 1; } let a = 1,b=1; let Fn = 0; for(let i = 3; i <= n; i++){ Fn = a+b; a = b; b = Fn; } return Fn; } console.log(fib(Number(line.trim()))); } }()
#include<iostream> using namespace std; int main() { int a[47],k; cin>>k; for(int i=2;i<=k;i++) { a[0]=1; a[1]=1; a[i]=a[i-1]+a[i-2]; } cout<<a[k-1]<<endl; }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String s = reader.readLine(); System.out.println(fbnq(Integer.parseInt(s))); } public static int fbnq(int s) { if (s <= 2) return 1; return fbnq(s - 1) + fbnq(s - 2); } }
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); //System.out.println("请输入一个整数(0<k<47):"); int k = sc.nextInt(); if(k <= 0 || k >= 47){ //System.out.println("您输入的整数有误,请重新输入:):"); k = sc.nextInt(); } System.out.println(fun(k)); } //递归法 public static int fun(int num){ if(num == 1 || num == 2){ return 1; } return fun(num - 1) + fun(num - 2); } }
矩阵乘法解决,保证时间复杂度为O(logN)
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int n = k - 2;
if (n <= 2) {
System.out.println(1);
return;
}
int[][] matrix = new int[][]{{1, 1}, {1, 0}};
matrix = matrixPower(matrix, n);
int result = matrix[0][0] + matrix[1][0];
System.out.println(result);
}
private static int[][] matrixPower(int[][] m, int n) {
int[][] result = new int[m.length][m[0].length];
for (int i = 0; i < m.length; i++) {
result[i][i] = 1;
}
while (n != 0) {
result = (n & 1) == 1 ? matrixMultiply(result, m) : result;
m = matrixMultiply(m, m);
n >>= 1;
}
return result;
}
private static int[][] matrixMultiply(int[][] a, int[][] b) {
if (a[0].length != b.length)
return null;
int[][] result = new int[a.length][b[0].length];
for (int row = 0; row < a.length; row++) {
for (int column = 0; column < b[0].length; column++) {
int temp = 0;
for (int i = 0; i < a[row].length; i++) {
temp += a[row][i] * b[i][column];
}
result[row][column] = temp;
}
}
return result;
}
}
#include<stdio.h> int main(){ int i,n,t1=0,t2=1,nextTerm; while( scanf("%d",&n)!=EOF){ for(i=1;i<=n;i++){ nextTerm=t1+t2; t1=t2; t2=nextTerm; } printf("%d",t1); } return 0; }