What is iterative and recursive algorithms? What is the difference between the two?

Source: Internet
Author: User

Iterative algorithms are a basic method for solving problems with computers. It allows computers to execute a group of commands (or a certain step) repeatedly and execute these commands (or these steps) at a time by taking advantage of the high computing speed and the ability to perform repetitive operations) the original value of the variable.

To solve the problem using iterative algorithms, we need to do the following three aspects:

1. Determine the iteration variable. Among the problems that can be solved by iterative algorithms, there is at least one variable that is directly or indirectly recursive from the old value to the new value. This variable is the iteration variable.

2. Establish an iterative relationship. The so-called iterative relationship refers to how to derive the formula (or relationship) of the next value from the previous value of the variable ). The establishment of the iteration relationship is the key to solving the iteration problem. It can usually be done using a recursive or inverted method.

3. Control the iteration process. When will the iteration end? This is an issue that must be considered when writing iterative programs. The iteration process cannot be repeated endlessly. Iteration process control is usually
There are two possible situations: one is that the number of required iterations is a definite value and can be calculated; the other is that the number of required iterations cannot be determined. In the previous case, you can build a fixed number of cycles to achieve
Control the iteration process. In the latter case, the conditions used to end the iteration process need to be further analyzed.

Example 1: a new breed of rabbit was introduced in a farm. The rabbit was born every month from the next month. If all rabbits do not die, how many rabbits are there in the farm in 12th months?

Analysis: this is a typical recursive problem. Assume that the number of rabbits in 1st months is u 1, the number of rabbits in 2nd months is U 2, and the number of rabbits in 3rd months is U 3 ,...... According to the question, "this rabbit has been born every month since the next month ."

The following is a reference clip:
U 1 = 1, U 2 = u 1 + u 1 × 1 = 2, U 3 = U 2 + U 2 × 1 = 4 ,......

According to this rule, we can sum up the following recursive formula:

The following is a reference clip:
U n = u n-1 × 2 (n ≥ 2)

Corresponding to u n and u n-1, two iteration variables y and X are defined. The above recursive formula can be converted into the following iteration relationship:

The following is a reference clip:
Y = x * 2
X = y

Let the computer repeat this iteration 11 times to calculate the number of rabbits in 12th months. The reference procedure is as follows:

The following is a reference clip:
CLS
X = 1
For I = 2 to 12
Y = x * 2
X = y
Next I
Print y
End

Example 2: amoeba breeds in simple split mode. It takes 3 minutes for each split. Put several amoeba in a container filled with nutrient parameters. After 45 minutes, the container is filled with amoeba. It is known that up to 20 amoeba containers can be installed. Question: How many amoeba files were put in the container at the beginning? Compile the program.

Analysis: According to the question, amoeba splits every three minutes. From the very beginning, amoeba is placed into the container and is filled with containers after 45 minutes.
45/3 = 15 times. "A container can hold up to two or 20 amoeba containers." That is, the number of amoeba containers generated after 15 splits is 2 and 20.
. The subject requires us to calculate the number of amodives before the split. We may wish to use the reverse push method, from 2 to 20 after the 15th split, to roll back before the 15th split (that is, 14th
After the second split), and then roll back after 13th split, after 12th split ,...... The number before the first split.

Set the number before 1st split to x 0, the number after 1st split to x 1, and the number after 2nd split to X 2 ,...... If the number after 15th split is x 15

The following is a reference clip:
X 14 = x 15/2, x 13 = x 14/2 ,...... X n-1 = x n/2 (n ≥ 1)

Because the number x 15 after the first split is known, if the iteration variable is defined as X, you can convert the above inverse formula into the following iteration formula:

X = X/2 (the initial value of X is the number of 15th splits after 2 20)

By repeating this iteration formula for 15 times, we can roll out the number of amoeba before the first split. Because the number of iterations is a definite value, we can use a fixed number of cycles to control the iteration process. The reference procedure is as follows:

The following is a reference clip:
CLS
X = 2 ^ 20
For I = 1 to 15
X = X/2
Next I
Print x
End

: Use C ++ to control the switch of the DVD/CD drive

 

Example 3: Verify the valley angle conjecture. A strange phenomenon was discovered by a Japanese mathematician Gu jiajingfu when studying natural numbers: For any natural number N, if n is an even number, divide it
2. If n is an odd number, multiply it by 3 and then add 1. After a finite operation, we can get the natural number 1. People call this discovery of Gu jiaojingfu a "Gu Jiao conjecture ".

Requirement: write a program, input a natural number N on the keyboard, and print the entire process of N after a finite operation.

Analysis: the iteration variable is defined as N. According to the content of the grain angle conjecture, the iteration relationship can be obtained in two cases: when n is an even number, n = n/2; when N is an odd number, n = N * 3 + 1. The description in QBASIC is as follows:

The following is a reference clip:
If n is an even number of then
N = n/2
Else
N = N * 3 + 1
End if

This is the iterative process that requires repeated execution by the computer. How many times does this iteration process need to be repeated to make iteration Variable N eventually become a natural number 1
This is something we cannot calculate. Therefore, it is necessary to further determine the conditions used to end the iteration process. By carefully analyzing the question requirements, it is not difficult to see that for any given natural number n
After a finite operation, you can obtain the natural number 1, and the verification has been completed. Therefore, the condition used to end the iteration process can be defined as: n = 1. The reference procedure is as follows:

The following is a reference clip:
CLS
Input "Please input n ="; n
Do until n = 1
If n mod 2 = 0 then
Rem if n is an even number, call the iteration formula n = n/2.
N = n/2
Print "-"; N;
Else
N = N * 3 + 1
Print "-"; N;
End if
Loop
End

Iteration Method

Iteration Method is a common algorithm design method used to obtain the approximate root of equations or equations. Set the equation to f (x) = 0, use a mathematical method to export the equivalent form X = g (x), and then follow these steps:

(1) Select the approximate root of an equation and assign it to variable x0;

(2) Save the value of x0 to the variable X1, calculate g (X1), and save the result to the variable x0;

(3) when the absolute value of the difference between x0 and X1 is smaller than the specified precision requirement, repeat the calculation in step (2.

If the equation has roots and the approximate root sequence obtained by the above method converges, The x0 obtained by the above method is considered as the root of the equation. The above algorithm is represented in the form of a C program:

[Algorithm] iterative method is used to find the root of the equation.

The following is a reference clip:
{X0 = initial approximate root;
Do {
X1 = x0;
X0 = g (X1);/* calculate a new approximate root based on a specific equation */
} While (FABS (x0-x1)> epsilon );
Printf ("the approximate root of the equation is % F/N", X0 );
}

Iterative algorithms are also often used to find the root of the equations.

X = (x0, X1 ,..., Xn-1)

Set the equations:

Xi = GI (x) (I = 0, 1 ,..., N-1)

The Iterative Algorithm for Finding the root of the equations can be described as follows:

[Algorithm] iterative method is used to obtain the root of the equations.

The following is a reference clip:
{For (I = 0; I
X = initial approximate root;
Do {
For (I = 0; I
Y = X;
For (I = 0; I
X = GI (X );
For (delta = 0.0, I = 0; I
If (FABS (Y-x)> delta) Delta = FABS (Y-x );
} While (delta> epsilon );
For (I = 0; I
Printf ("the approximate root of variable X [% d] is % F", I, X );
Printf ("/N ");
}

Pay attention to the following two possible situations when using iterative methods to root out:

(1) If the equation has no solution, the approximate root sequence obtained by the algorithm will not converge, and the iteration process will become an endless loop. Therefore, before using the iterative algorithm, we should first check whether the equation has a solution, limit the number of iterations in the program;

(2) Although the equation has solutions, improper selection of iteration formulas or unreasonable selection of the initial approximate root of iteration may also lead to iteration failure.

Recursion

Recursion is a powerful tool for designing and describing algorithms. Because it is often used in the description of complex algorithms, we will discuss it before introducing other algorithm design methods.

Algorithms that can use recursive descriptions usually have the following features: To solve the n-scale problem, we try to break it down into smaller-scale problems, then, we can easily construct a solution to these small problems,
In addition, these smaller problems can also be resolved into smaller problems using the same decomposition and synthesis method, and the solutions to larger problems can be created from the deconstruct of these smaller problems. In particular, when the scale N is 1
Directly solve the problem.

: Formatted display of floating point numbers in C ++

 

[Problem] compile the nth function fib (n) for calculating the Fibonacci series ).

Fibonacci series: 0, 1, 1, 2, 3 ,......, That is:

The following is a reference clip:
FIB (0) = 0;
FIB (1) = 1;
FIB (n) = fib (n-1) + fib (n-2) (when n> 1 ).

Recursive functions:

The following is a reference clip:
Int fib (int n)
{If (n = 0) return 0;
If (n = 1) return 1;
If (n> 1) return fib (n-1) + fib (n-2 );
}

The execution process of recursive algorithms is divided into two stages: recursive and regression. In the recurrence stage, the solution of more complex problems (scale N) is pushed to the solution of problems that are simpler than the original problem (scale less than N. Example
In the above example, the FIB (n) is solved and pushed to the FIB (n-1) and FIB (n-2) solutions ). That is to say, to calculate fib (N), you must calculate fib (n-1) and
FIB (n-
2), while the calculation of Fib (n-1) and FIB (n-2), must first calculate fib (n-3) and FIB (n-4 ). And so on until the calculation of Fib (1) and FIB (0), points
Do not get results 1 and 0 immediately. In the recurrence stage, termination of recursion is required. For example, in function fib, when n is 1 and 0.

In the regression phase, after obtaining the solution of the simplest case, return the result step by step and obtain the solution of a slightly complex problem, for example, after obtaining fib (1) and FIB (0, the result of Fib (2) is returned ,......, After obtaining the results of Fib (n-1) and FIB (n-2), the results of Fib (n) are returned.

When writing recursive functions, note that the knowledge of local variables and parameters in the functions is limited to the current call layer. When recursion enters the simple problem layer, parameters and local variables at the original level are hidden. In a series of "simple question" layers, they have their own parameters and local variables.

Due to recursion, a series of function calls and a series of repeated computations may occur, the execution efficiency of recursive algorithms is relatively low. When a recursive algorithm can be easily converted into a recursive algorithm
Write programs by recursive algorithms. For example, for the above example, the function fib (n) of the nth item of the Fibonacci series should adopt a recursive algorithm, that is, the next item is calculated from the first two items of the Fibonacci series, straight
To calculate the required n.

[Problem] combination Problem

Problem description: Find the natural numbers 1, 2 ,...... And N. For example, all the combinations of N = 5 and r = 3 are: (1) 5, 4, 3 (2) 5, 4, 2 (3) 5, 4, 1

(4) 5, 3, 2 (5) 5, 3, 1 (6) 5, 2, 1

(7) 4, 3, 2 (8) 4, 3, 1 (9) 4, 2, 1

(10) 3, 2, 1

The ten combinations listed in the analysis can be used to consider the algorithm of the composite function. Set the function to void comb (int m, int
K) to find the natural numbers 1, 2 ,...... And any combination of K numbers in M. When the first number of a combination is selected, the following number is a combination of the number of K-1 from the remaining number of m-1. This will calculate m
The combination problem of K number in the number is transformed into the problem of the combination problem of the number of m-1 and the number of K-1. Set function to introduce work array [
] Stores the numbers of the obtained combinations. The Convention function puts the first number of the K-digit combination in a [K]. After a combination is obtained, [
. The first number can be m m-1 ,...... , K, the function puts the first number of the combination into the array, there are two possible options, because the remaining elements of the combination have not been removed, continue to pass
Return to confirm; or because all elements of the combination have been determined, output the combination. For details, see the function comb in the following program.

[Program]

The following is a reference clip:
# Include
# Define maxn100
Int A [maxn];
Void comb (int m, int K)
{Int I, J;
For (I = m; I> = K; I --)
{A [k] = I;
If (k> 1)
Comb (I-1, k-1 );
Else
{For (j = A [0]; j> 0; j --)
Printf ("% 4D", a [J]);
Printf ("/N ");
}
}
}
Void main ()
{A [0] = 3;
Comb (5, 3 );
}

[Problem] backpack Problems

Problem description: N items with different values and weights are selected from the N items, so that the total weight of the selected item does not exceed the specified weight limit, but the total value of the selected item is the largest.

Set n
Item weight: w0, W1 ,... , Wn-1, item values are v0, V1 ,... Vn-1. Use recursive item search options. There are a variety of options, and
The solution with the largest total value is stored in the array option [], and the total value of the solution is stored in the variable maxv. The new scheme is being investigated, and the item selection is saved in the array COP [
]. Assuming that the current scheme has taken into account the items of the previous I-1, it is now necessary to take into account item I; the sum of the weight of the items included in the current scheme is TW; so far, if other items are selected as possible, this solution can achieve
The expected value of the total value is TV. When TV is introduced to an algorithm, once the expected value of the total value of the current scheme is smaller than the total value of maxv in the preceding scheme, it should be terminated to continue to investigate the meaningless work of the current scheme.
For the current scheme, check the next scheme immediately. Because the total value of the solution is no larger than that of maxv, this solution will not be further investigated. This also ensures that the solution found after the function is better than the previous solution.

There are two possible options for the I-th item:

(1) considering that item I is selected, this possibility is feasible only when it does not exceed the total weight limit of the solution. After selection, continue to recursively consider the selection of other items.

(2) consider that item I is not selected. This possibility is only when item I is not included, and a more valuable solution may be found.

Write the recursive algorithm as follows:

The following is a reference clip:
Try)
{/* Consider the possibility that item I is included in the current plan */
If (including item I is acceptable)
{Include item I in the current plan;
If (I
Try (I + 1, TW + item I weight, TV );
Else
/* Another complete solution, because it is better than the previous solution and uses it as the best solution */
Save the current scheme as the temporary best scheme;
Restore the exclusive state of item I;
}
/* Consider the possibility that item I is not included in the current plan */
If (excluding items I can only be considered by male)
If (I
Try (I + 1, TW, TV-item I value );
Else
/* Another complete solution, because it is better than the previous solution, uses it as the best solution */
Save the current scheme as the temporary best scheme;
}

: Visual C ++ compiler common options

 

Basic concepts and features of Recursion

The Programming Technique of program calling itself is called recursion ).

A process or function directly or indirectly calls itself in its definition or description, it usually converts a large and complex problem into a small problem similar to the original problem.
Solution: the recursive policy can describe multiple repeated computations required in the Problem Solving Process with only a small number of programs, greatly reducing the amount of code in the program. The ability to recursion lies in the use of limited statements to define an infinite set of objects. Delivery
The program written by thinking is often very concise and easy to understand.

In general, recursion requires boundary conditions, recursive forward segments, and recursive return segments. If the boundary condition is not met, recursive advances. If the boundary condition is met, recursive returns.

Note:

(1) recursion is to call itself in a process or function;

2) When using an incremental strategy, there must be a clear recursive termination condition called the recursive exit.

 

To understand the preceding algorithm, we recommend the following examples. There are four items. their weight and value are shown in the table:

Item 0 1 2 3

Weight 5 3 2 1

Value 4 4 3 1

And set the weight to 7. The above algorithm indicates the process of finding the solution. From the graph, once a solution is found, the algorithm is further improved. If it can be determined that a search branch does not find a better solution, the algorithm does not continue to search for the branch, but immediately terminates the branch and examines the next branch.

Compile functions and programs based on the above algorithms as follows:

[Program]

The following is a reference clip:
# Include
# Define n 100
Double limitw, totv, maxv;
Int option [N], COP [N];
Struct {double weight;
Double value;
} A [n];
Int N;
Void find (int I, double TW, double TV)
{Int K;
/* Consider the possibility that item I is included in the current plan */
If (TW + A. weight <= limitw)
{COP = 1;
If (I
Else
{For (k = 0; k
Option [k] = COP [k];
Maxv = TV;
}
COP = 0;
}
/* Consider the possibility that item I is not included in the current plan */
If (tv-a.value> maxv)
If (I
Else
{For (k = 0; k
Option [k] = COP [k];
Maxv = tv-a.value;
}
}
Void main ()
{Int K;
Double W, V;
Printf ("number of input items/N ");
Scanf ("% d", & N );
Printf ("input the weight and value of each item/N ");
For (totv = 0.0, K = 0; k
{Scanf ("% 1f % 1f", & W, & V );
A [K]. Weight = W;
A [K]. value = V;
Totv + = V;
}
Printf ("Input weight limit/N ");
Scanf ("% 1f", & limitv );
Maxv = 0.0;
For (k = 0; k find (0, 0.0, totv );
For (k = 0; k
If (Option [k]) printf ("% 4D", k + 1 );
Printf ("/n total value %. 2f/N", maxv );
}

In comparison, we will consider non-recursive program solutions using the same solution. In order to increase the search speed, the program does not simply generate all the solutions one by one, but the impact of each item on the solution.
A solution is worth further consideration. One solution is formed by examining each item in sequence. The investigation of item I involves the following situations: when the item is included in the solution, the total weight of the solution is still satisfied.
This item should be included in the solution. Otherwise, this item should not be included in the solution currently being formed. Similarly, when an item is not included in the solution, it is still possible to find
Currently, when the temporary optimal solution is better, this item is not included in the solution. On the contrary, the solution that this item is not included in the current solution should not be considered. For any party that deserves further consideration
Program to further consider the next item.

[Program]

The following is a reference clip:
# Include
# Define n 100
Double limitw;
Int COP [N];
Struct ele {double weight;
Double value;
} A [n];
Int K, N;
Struct {int;
Double TW;
Double TV;
} Twv [N];
Void next (int I, double TW, double TV)
{Twv. = 1;
Twv.tw = TW;
Twv. TV = TV;
}
Double find (struct ele * a, int N)
{Int I, K, F;
Double maxv, TW, TV, totv;
Maxv = 0;
For (totv = 0.0, K = 0; k
Totv + = A [K]. value;
Next (0, 0.0, totv );
I = 0;
While (I> = 0)
{F = twv .;
Tw = twv.tw;
TV = twv. TV;
Switch (f)
{Case 1: twv. ++;
If (TW + A. weight <= limitw)
If (I
{Next (I + 1, TW + A. Weight, TV );
I ++;
}
Else
{Maxv = TV;
For (k = 0; k
COP [k] = twv [K].! = 0;
}
Break;
Case 0: I --;
Break;
Default: twv. = 0;
If (tv-a.value> maxv)
If (I
{Next (I + 1, TW, tv-a.value );
I ++;
}
Else
{Maxv = tv-a.value;
For (k = 0; k
COP [k] = twv [K].! = 0;
}
Break;
}
}
Return maxv;
}
Void main ()
{Double maxv;
Printf ("number of input items/N ");
Scanf ("% d", & N );
Printf ("Input weight limit/N ");
Scanf ("% 1f", & limitw );
Printf ("input the weight and value of each item/N ");
For (k = 0; k
Scanf ("% 1f % 1f", & A [K]. Weight, & A [K]. value );
Maxv = find (A, N );
Printf ("/n selected items are/N ");
For (k = 0; k
If (Option [k]) printf ("% 4D", k + 1 );
Printf ("/n total value %. 2f/N", maxv );
}

: Use C language code in Delphi programming

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.