Common algorithms (C Edition)

Source: Internet
Author: User
Tags ibase

Algorithm (algorithm): basic ideas, methods, and steps for solving computer problems. Algorithm Description: describes the methods and steps taken to solve a problem or to complete a task, including the required data (input data and output results) what structure is used, what statements are used, and how to arrange these statements. Generally, the algorithm is described using natural language, structured flowchart, and pseudocode.

I. Simple algorithms for counting, summation, and factorial

Cycle is used for such problems. You must determine the initial value, end value, or end condition of the cyclic variable based on the problem. You must also pay attention to the initial value of the variable used to represent the count, sum, and factorial.

For example, a random function is used to generate 100 random integers in the range of [0, 99]. The numbers in a single digit are 1, 2, 3, 4, 5, 6, 7, 8, respectively, and print out the numbers of 9 and 0.

This topic uses Arrays for processing. array a [100] is used to store 100 random integers. array X [10] is used to store numbers of 1, 2, 3, 4, 5, 6, respectively, the number of numbers 7, 8, 9, and 0. That is, the number of a single digit is 1 in X [1], and the number of a single digit is 2 in X [2 ,...... The number of digits with a single digit of 0 is stored in X [10].

Void main ()
{Int A [101], X [11], I, P;
For (I = 0; I <= 11; I ++)
X [I] = 0;
For (I = 1; I <= 100; I ++)
{A [I] = rand () %100;
Printf ("% 4D", a [I]);
If (I % 10 = 0) printf ("/N ");
}
For (I = 1; I <= 100; I ++)
{P = A [I] % 10;
If (P = 0) P = 10;
X [p] = x [p] + 1;
}
For (I = 1; I <= 10; I ++)
{P = I;
If (I = 10) p = 0;
Printf ("% d, % d/N", P, X [I]);
}
Printf ("/N ");
}

2. Calculate the maximum common divisor and least common multiple of two integers.

Analysis: the algorithm for finding the maximum common approx: (least common multiples = product of two integers/maximum common approx)
(1) For known two numbers m, n, making M> N;
(2) divide m by N to obtain the remainder R;
(3) If r = 0, n is the obtained maximum common approx. The algorithm ends; otherwise, the algorithm is executed (4 );
(4) M records N, N records R, and then repeated execution (2 ).
For example, evaluate M = 14, n = 6, the maximum public approx. m n r
14 6 2
6 2 0
Void main ()
{Int nm, R, n, m, T;
Printf ("Please input two numbers:/N ");
Scanf ("% d, % d", & M, & N );
Nm = N * m;
If (M <n)
{T = N; n = m; M = T ;}
R = m % N;
While (R! = 0)
{M = N; n = r; r = m % N ;}
Printf ("maximum common Appointment: % d/N", N );
Printf ("minimum public multiple: % d/N", nm/N );
}

3. Determine prime numbers

The number that can only be divided by 1 or itself is called the basic idea of prime number: Use m as the divisor, and use 2-int () as the divisor. If they are not all divided, M is the prime number, otherwise it is not. (Available in the following sections)
Void main ()
{Int m, I, K;
Printf ("Please input a number:/N ");
Scanf ("% d", & M );
K = SQRT (m );
For (I = 2; I <K; I ++)
If (M % I = 0) break;
If (I> = K)
Printf ("this number is a prime number ");
Else
Printf ("this number is not a prime number ");
}
Write it into a function. If it is a prime number, 1 is returned. If it is not, 0 is returned.
Int prime (M %)
{Int I, K;
K = SQRT (m );
For (I = 2; I <K; I ++)
If (M % I = 0) return 0;
Return 1;
}

4. Verify godebach's Conjecture

(Any even number greater than or equal to 6 can be divided into the sum of two prime numbers)
Basic Idea: If n is an even number greater than or equal to 6, it can be divided into two numbers: N1 and N2. Check whether N1 and N2 are prime numbers. If they are both, they are a group of solutions. If N1 is not a prime number, you do not have to check whether N2 is a prime number. First from n1 = 3, check whether N1 and N2 (n2 = N-n1) are prime numbers. Then enable N1 + 2 to check whether N1 and N2 are prime numbers ,... Until n1 = n/2.

Using the above prime function, the program code used to verify the godebach conjecture is as follows:
# Include "math. H"
Int prime (INT m)
{Int I, K;
K = SQRT (m );
For (I = 2; I <K; I ++)
If (M % I = 0) break;
If (I> = K)
Return 1;
Else
Return 0;
}

Main ()
{Int X, I;
Printf ("Please input a even number (> = 6):/N ");
Scanf ("% d", & X );
If (x <6 | x % 2! = 0)
Printf ("data error! /N ");
Else
For (I = 2; I <= X/2; I ++)
If (prime (I) & prime (X-I ))
{
Printf ("% d + % d/N", I, X-I );
Printf ("Verification Successful! ");
Break;
}
}

V. sorting problems

1. sort by selection (ascending)

Basic Idea:
1) For a sequence with N numbers (stored in array a (n), the minimum number is selected and the position is exchanged with the 1st number;
2) except for 1st, the smallest number is selected among the other n-1 numbers, and the position is exchanged with 2nd;
3) and so on. After N-1 is selected, the sequence is sorted in ascending order.

The program code is as follows:
Void main ()
{Int I, j, Imin, S, A [10];
Printf ("/N input 10 numbers:/N ");
For (I = 0; I <10; I ++)
Scanf ("% d", & A [I]);
For (I = 0; I <9; I ++)
{Imin = I;
For (j = I + 1; j <10; j ++)
If (A [Imin]> A [J]) Imin = J;
If (I! = Imin)
{S = A [I]; A [I] = A [Imin]; A [Imin] = s ;}
Printf ("% d/N", a [I]);
}
}

2. bubble sort (ascending)

Basic Idea: (compare two adjacent numbers and adjust them to the front if they are small)
1) There are n numbers (stored in array a (n). The first line is to compare each adjacent two numbers, and a small value is adjusted to the front. After the n-1 adjacent comparisons, the maximum number is already "bottom", placed in the last position, and the decimal point is "floating up ";
2) the second round of the remaining n-1 number (the maximum number has been "bottom") by the above method comparison, the number of times after the N-2 times of two adjacent comparison;
3) by analogy, N numbers are compared in a total of N-1 bits, and n-J times are compared in the J bits.
The program section is as follows:
Void main ()
{Int A [10];
Int I, j, T;
Printf ("input 10 numbers/N ");
For (I = 0; I <10; I ++)
Scanf ("% d", & A [I]);
Printf ("/N ");
For (j = 0; j <= 8; j ++)
For (I = 0; I <9-j; I ++)
If (A [I]> A [I + 1])
{T = A [I]; A [I] = A [I + 1]; A [I + 1] = T ;}
Printf ("the sorted numbers:/N ");
For (I = 0; I <10; I ++)
Printf ("% d/N", a [I]);
}

3. sort by merging (merge two ordered arrays A and B into another ordered array C in ascending order)

Basic Idea:
1) Compare the first element in array A and array B, and add small elements to array C;
2) Compare the next element in the array where the small element is located with the larger element after the previous comparison in the other array. Repeat the above comparison process until an array is ranked first;
3) copy the remaining elements of another array into the C array and complete the merging and sorting.
The program section is as follows:
Void main ()
{Int A [10], B [10], C [20], I, IA, IB, IC;
Printf ("Please input the first array:/N ");
For (I = 0; I <10; I ++)
Scanf ("% d", & A [I]);
For (I = 0; I <10; I ++)
Scanf ("% d", & B [I]);
Printf ("/N ");
IA = 0; IB = 0; Ic = 0;
While (IA <10 & IB <10)
{If (a [Ia] <B [IB])
{C [IC] = A [Ia]; IA ++ ;}
Else
{C [IC] = B [IB]; IB ++ ;}
IC ++;
}
While (IA <= 9)
{C [IC] = A [Ia];
IA ++; IC ++;
}
While (ib <= 9)
{C [IC] = B [IB];
B ++; IC ++;
}
For (I = 0; I <20; I ++)
Printf ("% d/N", C [I]);
}

6. Search for Problems

1. ① sequential Lookup (search for a certain number of X columns)

Basic Idea: place a column in array a [1] --- A [n], put the number to be searched in array X, and compare the elements of array X and array a from start to end. Use the Variable P to represent the element subscript of array A. The initial value of P is 1, so that X is compared with a [p]. If X is not equal to a [p], P = p + 1, repeat this process continuously. Once X is equal to a [p], the loop is exited. In addition, if p is greater than the array length, the loop should also be stopped. (This process can be implemented by the following statement)
Void main ()
{Int A [10], p, X, I;
Printf ("Please input the array:/N ");
For (I = 0; I <10; I ++)
Scanf ("% d", & A [I]);
Printf ("Please input the number you want find:/N ");
Scanf ("% d", & X );
Printf ("/N ");
P = 0;
While (X! = A [p] & P <10)
P ++;
If (P> = 10)
Printf ("the number is not found! /N ");
Else
Printf ("the number is found the no % d! /N ", P );
}
Thought: rewrite the search function "find" in the above program. If it is found, the lower mark value is returned. If it is not found,-1 is returned.
② Basic idea: place a column in array a [1] --- A [n], the key value to be searched is the key, and compare the key with the elements in array a from start to end, if they are the same, the search is successful. If they cannot be found, the search fails. (The procedure is as follows. Index: stores the subscript of the element to be found .)
Void main ()
{Int A [10], index, X, I;
Printf ("Please input the array:/N ");
For (I = 0; I <10; I ++)
Scanf ("% d", & A [I]);
Printf ("Please input the number you want find:/N ");
Scanf ("% d", & X );
Printf ("/N ");
Index =-1;
For (I = 0; I <10; I ++)
If (x = A [I])
{Index = I; break;
}
If (Index =-1)
Printf ("the number is not found! /N ");
Else
Printf ("the number is found the no % d! /N ", index );
}

2. Semi-query (only sequential series can be searched)

Basic Idea: set N orders (from small to large) to be stored in array a [1] ---- A [n]. The number to be searched is X. Use the variables bot, top, and mid to indicate the bottom (lower-bound array), top (upper-bound array), and center of the data range, mid = (top + BOT)/2, respectively, the half-lookup algorithm is as follows:
(1) x = a (MID), the exit loop is found; otherwise, the following judgment is made;
(2) x <A (MID), X must fall within the range of BOT and mid-1, that is, Top = mid-1;
(3) x> A (MID), X must fall within the range of Mid + 1 and top, that is, bot = Mid + 1;
(4) After a new search range is determined, repeat the above comparison until it is found or bot <= top.
Write the above algorithm into the following program:
Void main ()
{
Int A [10], mid, bot, top, X, I, find;
Printf ("Please input the array:/N ");
For (I = 0; I <10; I ++)
Scanf ("% d", & A [I]);
Printf ("Please input the number you want find:/N ");
Scanf ("% d", & X );
Printf ("/N ");
BOT = 0; Top = 9; find = 0;
While (BOT <top & find = 0)
{Mid = (top + BOT)/2;
If (x = A [Mid])
{Find = 1; break ;}
Else if (x <A [Mid])
Top = mid-1;
Else
BOT = Mid + 1;
}
If (find = 1)
Printf ("the number is found the no % d! /N ", mid );
Else
Printf ("the number is not found! /N ");
}

VII. Insertion Method

Insert a number into an ordered sequence. After insertion, the sequence is still ordered.

Basic Idea: N ordered numbers (from small to large) are stored in array A (1)-a (n) and the number X to be inserted. First, determine the position P where X is inserted in the array. (It can be implemented by the following statement)
# Define N 10
Void insert (int A [], int X)
{Int P, I;
P = 0;
While (x> A [p] & P <n)
P ++;
For (I = N; I> P; I --)
A [I] = A [I-1];
A [p] = X;
}
Main ()
{Int A [n + 1] = {1, 3, 4, 7, 8, 11, 13, 18, 56, 78}, X, I;
For (I = 0; I <n; I ++) printf ("% d,", a [I]);
Printf ("/ninput X :");
Scanf ("% d", & X );
Insert (a, X );
For (I = 0; I <= N; I ++) printf ("% d,", a [I]);
Printf ("/N ");
}

8. Matrix (two-dimensional array) Operations

(1) addition and subtraction of Matrices
C (I, j) = a (I, j) + B (I, j) Addition
C (I, j) = a (I, j)-B (I, j) Subtraction
(2) matrix multiplication
(Matrix A has M * l elements, and matrix B has L * n elements, then matrix C = a * B has M * n elements ). Any element in matrix C (I = 1, 2 ,..., M; j = 1, 2 ,..., N)
# Define M 2
# Define L 4
# Define N 3
Void mV (int A [m] [L], int B [l] [N], int C [m] [N])
{Int I, J, K;
For (I = 0; I <m; I ++)
For (j = 0; j <n; j ++)
{C [I] [J] = 0;
For (k = 0; k <L; k ++)
C [I] [J] + = A [I] [k] * B [k] [J];
}
}
Main ()
{Int A [m] [l] = {1, 2, 3, 4}, {1, 1 }};
Int B [l] [N] = {, 1}, {, 1}, {, 1}, {, 1 }}, c [m] [N];
Int I, J;
MV (A, B, C );
For (I = 0; I <m; I ++)
{For (j = 0; j <n; j ++)
Printf ("% 4D", C [I] [J]);
Printf ("/N ");
}
}
(3) matrix transfer
For example, a two-dimensional array A (5, 5) can be transposed in the following two ways:
# Define N 3
Void merge (INT a [n] [N])
{Int I, j, T;
For (I = 0; I <n; I ++)
For (j = I + 1; j <n; j ++)
{T = A [I] [J];
A [I] [J] = A [J] [I];
A [J] [I] = T;
}
}
Void CH2 (INT a [n] [N])
{Int I, j, T;
For (I = 1; I <n; I ++)
For (j = 0; j <I; j ++)
{T = A [I] [J];
A [I] [J] = A [J] [I];
A [J] [I] = T;
}
}
Main ()
{Int a [n] [N] = {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, I, j;
Round (a);/* or CH2 ();*/
For (I = 0; I <n; I ++)
{For (j = 0; j <n; j ++)
Printf ("% 4D", a [I] [J]);
Printf ("/N ");
}
}
(4) Evaluate the minimum element in a two-dimensional array and Its row and column
The basic idea is to use an array of the same dimension, which can be implemented using the following program section (take two-dimensional array a [3] [4] as an example ):
'Maximum, row, and column values are stored in variable Max.
# Define N 4
# Define m 3
Void min (int A [m] [N])
{Int min, row, column, I, J;
Min = A [0] [0];
Row = 0;
Column = 0;
For (I = 0; I <m; I ++)
For (j = 0; j <n; j ++)
If (A [I] [J] <min)
{Min = A [I] [J];
Row = I;
Column = J;
}
Printf ("min = % d/NAT row % d, column % d/N", Min, row, column );
}
Main ()
{Int A [m] [N] = {, 45,-5 }};
Min ();
}

IX. Iterative Method

Algorithm idea: for solving a problem X, a new value X1 can be obtained from a given initial value x0 based on an iteration formula, the new value X1 is closer to the required value x than the initial value x0. Then, the new value X1 → x0 is used as the initial value, and the original method is used to calculate X1, repeat this sum until | x1-x0 | <ε (a given precision ). In this case, X1 can be used as the solution to the problem.
For example, the square root of a number is obtained by iteration. The formula for finding the square root is:
# Include <math. h>
Float fsqrt (float)
{Float x0, x1;
X1 = A/2;
Do {
X0 = x1;
X1 = 0.5*(x0 + A/X0 );
} While (FABS (x1-x0)> 0.00001 );
Return (X1 );
}
Main ()
{Float;
Scanf ("% F", & );
Printf ("genhao = % F/N", fsqrt ());
}

10. Digital Conversion

Converts a decimal integer m to A → R (2-16) hexadecimal string.

Method: Remove m from R continuously until the quotient is zero and obtain the result in reverse order. The following is a conversion function. The IDEC parameter is a decimal number, and the iBase parameter is the base to be converted to a number (for example, the binary base is 2 and the octal base is 8 ), the function output result is a string.
Char * trdec (int idec, int IBASE)
{Char strdr [20], T;
Int I, IDR, P = 0;
While (IDEC! = 0)
{IDR = IDEC % IBASE;
If (IDR> = 10)
Strdr [p ++] = idr-10 + 65;
Else
Strdr [p ++] = IDR + 48;
IDEC/= IBASE;
}
For (I = 0; I <p/2; I ++)
{T = strdr [I];
Strdr [I] = strdr [p-i-1];
Strdr [p-i-1] = T;
}
Strdr [p] = '/0 ';
Return (strdr );
}
Main ()
{Int x, D;
Scanf ("% d", & X, & D );
Printf ("% s/n", trdec (x, D ));
}

11. General string processing

1. Simple encryption and decryption
The principle of encryption is to add (or subtract) an ordinal number k for each letter C, that is, replace it with the k letter after it. The conversion formula is C = C + K.
For example, if the ordinal number k is 5, then a → F, A → F, B →? G... When the letter after the ordinal number exceeds Z or Z, C = C + k-26
Example: You are good → DTZ fwj ltti
Reverse encryption process
Subtract (or add) a sequential number k for each letter C, that is, C = C-K,
For example, if the ordinal number k is 5, then Z → u, Z → u, y → T... C = C-K + 26 if the letter after the ordinal number is smaller than a or
The following program is encrypted:
# Include <stdio. h>
Char * jiami (char stri [])
{Int I = 0;
Char STRP [50], IA;
While (stri [I]! = '/0 ')
{If (stri [I]> = 'A' & stri [I] <= 'Z ')
{IA = stri [I] + 5;
If (IA> 'Z') IA-= 26;
}
Else if (stri [I]> = 'A' & stri [I] <= 'Z ')
{IA = stri [I] + 5;
If (IA> 'Z') IA-= 26;
}
Else IA = stri [I];
STRP [I ++] = IA;
}
STRP [I] = '/0 ';
Return (STRP );
}
Main ()
{Char s [50];
Gets (s );
Printf ("% s/n", jiami (s ));
}
2. count the number of text words
Enter a line of characters to count the number of words. Words are separated by cells.
Algorithm ideas:
(1) extract a character from the left of the text (string). Set the logic to "word" to indicate whether the obtained character is a character in the word. The initial value is set to 0.
(2) If the character is not a separator for words such as "space", "comma", "Semicolon", or "Exclamation point", then judge whether the word is 1, if the word value is not 1, the Table begins with a new word. Let the number of words num = num + 1, And let word = 1;
(3) If the characters used are delimiters of words such as "space", "comma", "Semicolon", or "Exclamation point", it indicates that the characters are not characters in the word, so that word = 0;
(4) take the next character in sequence, and then (2) (3) until the end of the text.
The following section describes the number of words contained in a string.
# Include "stdio. H"
Main ()
{Char C, string [80];
Int I, num = 0, word = 0;
Gets (string );
For (I = 0; (C = string [I])! = '/0'; I ++)
If (C = '') word = 0;
Else if (WORD = 0)
{Word = 1;
Num ++ ;}
Printf ("there are % d word in the line./N", num );
}

12. Exhaustion
  
The basic idea of the exhaustive method (also known as the enumeration method) is to list various possible situations one by one and determine which one is the solution that meets the requirements, this is a "method without other solutions" and the most "stupid" method. However, it often works for problems that cannot be solved by parsing, loop is usually used to solve the problem of exhaustion.
For example, if you want to change the equivalent value of RMB 100 to RMB 100 for each of the 5-yuan, 1-yuan, and 0.5-yuan notes, you must make no less than one note. Which combinations are there?
Main ()
{Int I, J, K;
Printf ("5 yuan 1 yuan 5 cents/N ");
For (I = 1; I <= 20; I ++)
For (j = 1; j <= 100-i; j ++)
{K = 100-i-j;
If (5 * I + 1 * j + 0.5 * k = 100)
Printf ("% 3d % 3d % 3d/N", I, j, k );
}
}

13. Recursive Algorithms
  
Describe itself with its own structure, called Recursion
  
VB allows you to call yourself within the definition of a sub-process and function process, that is, Recursive Sub-process and recursive function. Recursive processing is generally implemented using stacks. Each call is performed on itself, the current parameter is pushed to the stack until the recursion ends. The current parameter is popped up from the stack until the stack is empty.
Recursive conditions: (1) recursive end conditions and values at the end of the condition; (2) values can be expressed in recursion form and the recursion Develops Toward the termination condition.
For example, compile FAC (n) = n! Recursive functions
Int FAC (int n)
{If (n = 1)
Return (1 );
Else
Return (N * FAC (n-1 ));
}
Main ()
{Int N;
Scanf ("% d", & N );
Printf ("n! = % D/N ", FAC (n ));
}

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.