递推,迭代和递归求斐波那契数列
迭代
#include<stdio.h>
void main(){
int i,n,c,n1,n2,sum;
n1=n2=1;sum=2;
n=20;
for(i=3;i<=n;i++){
c=n1+n2;
n1=n2;
n2=c;
sum+=c;
}
printf("%d\n",c);
printf("%d",sum);
}
递推
#include<stdio.h>
void main(){
int n[20],sum=0,i;
n[0]=n[1]=1;
for(i=2;i<20;i++)
n[i]=n[i-1]+n[i-2];
for(i=0;i<20;i++)
sum+=n[i];
printf("%d\n",n[19]);
printf("%d",sum);
}
递归
#include<stdio.h>
int f(int x);
void main(){
int i,n,sum;
n=20;sum=0;
for(i=1;i<=n;i++)
sum+=f(i);
printf("%d\n",f(20));
printf("%d",sum);
}
int f(int x){
if(x<=2) return 1;
else return f(x-1)+f(x-2);
}
递归求杨辉三角
#include<stdio.h>
int yanghui(int i,int j)
{
int t;
if(i==0||i==j||j==0)
t=1;
else t=yanghui(i-1,j)+yanghui(i-1,j-1);
return t;
}
void main()
{
int i,j,row;
scanf("%d",&row);
for(i=0;i<row;i++)
{
for(j=0;j<row-i;j++)
printf(" ");
for(j=0;j<=i;j++)
printf("%d ",yanghui(i,j));
printf("\n");
}
}