Want to write something simple today-about computer algorithms

Source: Internet
Author: User
The Fibonacci sequence of computer algorithm design and analysis
无穷数列1,1,2,3,5,8,13,21,34,55,...,称为Fibonacci数列。关于它的三种方法:
① Simple Variable method

Set four variables, F1, F2, F, I and then combine the Loop completion algorithm (formerly 20 examples)

#include<studio.h>int mian(){int f1,f2,f,i;f1 = 1,f2 = 1;for(i = 1,i <= 20,i++){f = f1 + f2;  //传统迭代方法f1 = f2;f2 = f;}printf("%d",&f);return 0;}

Cons: Only the final result F is retained, and the median value is not saved simplified: Replace the For loop inside:

f2 = f1 + f2;f1 = f2 - f1;这样可以减少一个变量,只需要三个变量就可以了。
② Array

A one-dimensional integer array of length 20 can be defined with a for loop completion algorithm

#include<studio.h>int mian(){int f[20],i;for(int i = 0,i < 20,i++){    f[i] = f[i-1] +f[i-2];}printf("%d",&f[20]);return 0;}

Pros: You can save each value of an intermediate result

③ function
public static int fibonacci(int n){if(n <= 1)return 1;   //边界条件else return fibonacci(n-1) + fibonacci(n-2); //递归方程}#include<studio.h>void mian(){int n =20;printf("%d",fibonacci(n));return 0;}

Two conditions for using a function: ① recursive equation ② boundary condition

Want to write something simple today-about computer algorithms

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.