1, write the program, printing * Diamond
The number of blank spaces and * numbers to be printed in line I, printing each line in the For loop
Copy Code code as follows:
#include <stdio.h>
Print 2*n-1 lines in total, row by line
void Print1 (int n)
{
int i,j;
for (i=1;i<=n;i++) {//print 1 to N rows
for (j=1;j<=n-i;j++)//print n-i spaces
printf ("");
for (j=1;j<=2*i-1;j++)//Print 2*i-1 * number
printf ("*");
printf ("\ n");
}
for (; i<2*n;i++) {//print n+1 to 2*n-1 line, same (2*n-i) line
For (j=1;j<=n-(2*n-i); j + +)
printf ("");
For (j=1;j<=2* (2*n-i) -1;j++)
printf ("*");
printf ("\ n");
}
}
void Main ()
{
int n;//n is the number of * on the diamond Edge
printf ("Enter N:");
scanf ("%d", &n);
Print1 (n);
}
2, the Fibonacci sequence (Fibonacci Sequence), also known as the Golden Division Series, refers to such a series:
1, 1, 2, 3, 5, 8, 13, 、...... Mathematically, the Fibonacci sequence is defined as the following recursive method: F (0) =0,f (1) =1,f (n) =f (n-1) +f (n-2) (n>=2,n∈n*). Write a program that outputs the value of F (20).
Here are four different solutions, noting that there is a big difference between recursion and improved recursive efficiency.
Copy Code code as follows:
#include <stdio.h>
#include <math.h>
#include <time.h>
#define MAX 100
Recursion
int F1 (int n)
{
if (n==1 | | n==0)
return 1;
Return F1 (n-1) +f1 (n-2);
}
Improved recursion, eliminating repetitive computations
int F2 (int n)
{
To save an array of intermediate results
Static result[max]={1,1};
if (n==1 | | n==0)
return 1;
if (result[n-1] = = 0)
RESULT[N-1]=F2 (n-1);
if (result[n-2] = = 0)
RESULT[N-2]=F2 (n-2);
return result[n-1]+result[n-2];
}
Save intermediate results with arrays (from Chen Xiaojie)
int f3 (int n)
{
int a[max],i;
A[1]=1;
A[0]=1;
for (i=2;i<=n;i++)
A[I]=A[I-1]+A[I-2];
return a[n];
}
Iterations
int f4 (int n)
{
int i=2,a=1,b=1,sum=1;
while (i<=n) {
Sum=a+b;
A=b;
B=sum;
i++;
}
return sum;
}
void Main ()
{
Long Start,end;
Start=clock ();
printf ("F () ==%d\n", F1 (40));
End=clock ();
printf ("Spents:%d ms\n", End-start);
Start=clock ();
printf ("F () ==%d\n", F2 (40));
End=clock ();
printf ("Spents:%d ms\n", End-start);
Start=clock ();
printf ("F" ==%d\n, F3 (20));
End=clock ();
printf ("Spents:%d ms\n", End-start);
Start=clock ();
printf ("F" ==%d\n, F4 (20));
End=clock ();
printf ("Spents:%d ms\n", End-start);
}
Run Result: