斐波那契数列求第n项的非递归算法实现
1 #include<iostream> 2 3 long long Fibonacci(unsigned int n){ 4 if(n<=2) 5 return n-1; 6 7 long long fibNumberOne = 1; 8 long long fibNumberTwo = 0; 9 long long fibN = 0; 10 for(unsigned int i = 2;i < n;i++){ 11 fibN = fibNumberOne + fibNumberTwo; 12 fibNumberTwo = fibNumberOne; 13 fibNumberOne = fibN; 14 } 15 return fibN; 16 } 17 18 int main(){ 19 unsigned int fiboNumber; 20 while(std::cin>>fiboNumber){ 21 std::cout<<Fibonacci(fiboNumber)<<std::endl; 22 } 23 return 0; 24 }
时间: 2024-12-10 03:15:45