Topic 1387: Fibonacci Sequence time limit: 1 seconds Memory limit: 32 Mega Special: No submission: 5415 Resolution: 1603 Title Description: We all know that the Fibonacci sequence is now required to input an integer n, please output the Fibonacci sequence nth. The Fibonacci sequence is defined as follows: input: The input may contain multiple test samples, and for each test case, the input includes an integer n (1<=n<=70). Output: Corresponds to each test case, outputting the value of the nth Xiang Feipo sequence. Sample input: 3 Sample output: 2
#include <iostream> #include <stdio.h>using namespace std;//Fibonacci sequence (recursive easy timeout) long long f (int n) { if (n==0) return 0; if (n==1) return 1; return f (n-1) +f (n-2);} Forwarding is returned as a cyclic long long F2 (int n) { if (n==0) return 0; if (n==1) return 1; Long long sum=0; Long Long preone=1;//n before a long long pretwo=0;//n the first two for (int i=2;i<=n;i++) { sum = preone+pretwo; Pretwo = PreOne; PreOne = sum; } return sum;} int main () { int n; while (scanf ("%d", &n)!=eof) { printf ("%ld\n", F2 (n)); } return 0;}
OB address
Sword refers to the offer series source code-Fibonacci sequence