斐波那契数列求第n个值的数?
斐波那契数列F0=0,F1=1,F2=1,F3=2......Fn=Fn-1+Fn-2;当输入第几行时,就输出第几行的数,如n=7时,就输出13,求教各位大佬,这个题怎么来写呢?
#include<stdio.h> int func(int n) { if (n == 0) return 0; if (n == 1) return 1; return func(n - 1) + func(n - 2); } int main() { int n = 0; scanf("%d", &n); printf("%d", func(n)); return 0; }
#include<stdio.h> int main() { int n = 0, i = 0, a[1000] = { 0 }; a[0] = 0; a[1] = 1; scanf("%d", &n); for (i = 2; i <= n; i++) { a[i] = a[i - 1] + a[i - 2]; } printf("%d", a[n]); return 0; }
unsigned fibonacci( const unsigned& first, const unsigned& second, size_t n ) { // a *= b #define MUL(a,b) do {\ unsigned t00 = a##00*b##00+a##01*b##10;\ unsigned t01 = a##00*b##01+a##01*b##11;\ unsigned t10 = a##10*b##00+a##11*b##10;\ unsigned t11 = a##10*b##01+a##11*b##11;\ a##00=t00, a##01=t01, a##10=t10, a##11=t11;\ } while(0) unsigned r00=1,r01=0,r10=0,r11=1; for( unsigned v00=0,v01=1,v10=1,v11=1; n!=0; n/=2 ) { if( n%2 == 1 ) MUL(r,v); // r*=v MUL(v,v); // v*=v; } return r00*first + r01*second; #undef MUL } #include <stdio.h> int main( void ) { printf( "f(0) = %u\n", fibonacci(0,1,0) ); printf( "f(1) = %u\n", fibonacci(0,1,1) ); printf( "f(2) = %u\n", fibonacci(0,1,2) ); printf( "f(3) = %u\n", fibonacci(0,1,3) ); printf( "f(7) = %u\n", fibonacci(0,1,7) ); }