C-language cycle small algorithm

Source: Internet
Author: User

1. Prime number Judgment

For this, many people may write this directly:


View plain Copy to clipboard print?   int isprime (int n)//function returns 1 expression is prime number, return 0 means not prime number {int i;   for (i = 2; i < n; i++) if (n% i = = 0) break;   return i >= N; the int isprime (int n)//function returns 1 to indicate the prime number, and returns 0 to indicate that it is not prime {int i; for (i = 2; i < n; i++) if (n% i = = 0) break; return i >= N; }


Or, some people know the optimization of square roots:
View plain Copy to clipboard print?   int isprime (int n) {int I, s = (int) (sqrt (double) n) + 0.01);   for (i = 2; I <= s; i++) if (n% i = = 0) break;   return i > S; int isprime (int n) {int I, s = (int) (sqrt (double) n) + 0.01); for (i = 2; I <= s; i++) if (n% i = = 0) break; retu RN i > S; }
Or, eliminate even:
View plain Copy to clipboard print?   int isprime (int n) {int I, s = (int) (sqrt (double) n) + 0.01);   if (n <= 3) return 1;   if (n% 2 = 0) return 0;   for (i = 3; I <= s; i + 2) if (n% i = = 0) break;   return i > S; int isprime (int n) {int I, s = (int) (sqrt ((double) n) + 0.01); if (n <= 3) return 1; if (n% 2 = 0) return 0; (i = 3; I <= s; i = 2) if (n% i = = 0) break; return i > S; }
Of course, this is not enough, we can consider this fact:
All primes greater than 4, and the remainder of the 6 can only be 1 or 5.
For example, the next 5,7,11,13,17,19 are satisfied.

So, we can specialize first to judge 2 and 3
But then the problem comes up, because it's not simply incremental, and starting from 5 is +2,+4,+2,+4,.... This increments the
In this case, the loop should be how to write it.

First, we define a step, the loop is probably like this for (i = 5; I <= s; i + a)
So, that's each loop, let step from 2 to 4, or from 4 to 2
So, you can write this:
View plain Copy to clipboard print? #include  <stdio.h>    #include  <math.h>       int isprime ( int n)    {   int i, s =  (int) (sqrt ((double) n)  + 0.01),  step = 4;   if  (n <= 3)  return 1;   if  (n  % 2 == 0)  return 0;   if  (n % 3 == 0)   return 0;   for  (i = 5; i <= s; i += step)     {   if  (n % i == 0)    break;   step ^= 6;   }   return i > s;  }      int main ()    {   int n;   for  (n = 2; n < 100; ++n  //find  2 - 100  prime numbers and output    {&NBSP;&NBsp if  (IsPrime (n))  printf ("%d,",  n);  }   getchar ();   return 0;   }   #include <stdio.h> #include <math.h> int isprime (int n) {int I, s = (int) (sqrt (Do uble) n) + 0.01), step = 4; if (n <= 3) return 1; if (n% 2 = 0) return 0; if (n% 3 = 0) return 0; for (i = 5; I <= s; i + = Step) {if (n% i = = 0) Break, step ^= 6;} return i > S; int main () {int n; for (n = 2; n < ++n)//find 2-100 prime numbers and output {if (IsPrime (n)) printf ("%d,", n);} getchar (); re Turn 0; }
As above code, a step ^= 6; Complete step to convert between 2 and 4 (this ^ symbol is the XOR in C)
The reason is that 2 binary is 010,4 is 100,6 is 110, so 2 XOR or 4 gets 6:
2 ^ 4 => 6
6 ^ 2 => 4
6 ^ 4 => 2

So, by using XOR, you can construct loops that step back and forth between two values.
Study questions: The two-value cycle is the first, so how to construct a three-value or four-value loop.



2. Diamond Print

Many people, the idea of printing a diamond in the console is to split the diamond up and down, two very close to the code to print,
In fact, this code is very difficult to read, and not good reading
We know that the pattern to be printed is this:
*
***
*****
***
*

Meet the upper and lower symmetry, symmetrical, then, you can also get a double cycle, the same is symmetrical.
Very simply, first we have to put aside the habitual thinking that the for loop does not have to end at 0 or 0.
We can get loops from-C to c. So it's not easy to create a symmetric one. (Just take an absolute value)
We look at the center of the Diamond as coordinates 0, 0, and then we output the coordinates of the asterisk, which is |x| + |y| The point of <= C

This can be
View plain Copy to clipboard print? #include  <stdio.h>    #define &NBSP;IABS (x)   (  (x)  >= 0 ?  (x )  : -(x)  )  //defines a macro that calculates an absolute value    void print (int size)  //  Size is the radius of this diamond, and the diameter will be size * 2 + 1    {   int x, y;   for   (y = -size; y <= size; y++)    {   for  (x =  -size; x <= size; x++)    {   if  ( iabs (x)  +  iabs (y)  <= size ) The sum of the absolute values of  //x and y, i.e.  |x| + |y| <= size    Putchar (' * ');   else   putchar ('   ');  }   the Putchar (' \ n ');   }  }      int main ()    {   print (5);  // Output a diamond    GetChar () with a radius of 5 ();   return 0;  }   #include <stdio.h> #define IABS (x) (x) >= 0? (x):-(x))//define a macro void print (int size)/size that calculates the absolute value is the radius of the diamond, the diameter is size * 2 + 1 {int x, y; for (y =-size; y <= size; y++) {for (x =-size x <= size; x +) {if (Iabs (x) + iabs (y) <= size)//x and y the sum of their respective absolute values, that is, |x| + |y| <= size PUTC Har (' * '); else Putchar ('); } putchar (' \ n '); the int main () {print (5);//Output a diamond GetChar () with a radius of 5; return 0;}
What if I need to get a hollow diamond. Very very simple, because the dot on the diamond boundary, satisfies the |x| + |y| = = C
So, we just put that if the less than equal number, change to double equals number = = on it

Again, if I don't want the * number, I want the outermost layer to be the letter A, and then the first floor is B. That
A
ABA
ABCBA
ABA
A

So, we just do one character calculation in Putchar:
View plain Copy to clipboard print? Void print (int size)  // size is the radius of this diamond, the diameter will be size * 2 + 1    {    int x, y;   for  (y = -size; y <= size; y+ +)    {   for  (x = -size; x <= size; x++)    {    if  ( iabs (x)  + iabs (y)  <= size ) The sum of the absolute values of  //x and Y, that is,  | X| + |y| <= size    Putchar (  ' A '  +  size - iabs (x)  - iabs (y))    //Note the calculation method here    else   Putchar ('   ');  }    Putchar (' \ n ');  }  }   void print (int size)/size is the radius of this diamond, the diameter will be size * 2 + 1 {int x, y; for (y =-size y <= size; y++) {for (x =-size; x <= size; x +) {if (Iabs (x) + iabs (y) <= size) The sum of the respective absolute values of x and Y, i.e. |x| + |y| <= size Putchar (' A ' + (size-Iabs (x)-Iabs (y)); Pay attention to the calculation method here else Putchar ('); } putchar (' \ n '); } }
Similarly, if we are going to print the X-shaped:
*   *
* *
*
* *
*   *
Can also use this idea to complete, this question as study questions bar



3. Odd Order magic Square
The so-called Magic square (the most basic kind), is the horizontal, vertical, diagonal number and equal to a constant number of square
4 3 8
9 5 1
2 7 6

The above diagram, what is the rule. Easy to write code.

Let's copy this figure five times to the right and copy it down three times to expand it:

9 5 1 9, 5 1 9 5 1 9 5 1 9 5 1

Pay attention to the trend of blue numbers
How about, now.
It seems to be a lot more regularity now, but you don't think the loop is too good to write.
How do we know its coordinates directly from a given n?
It's not difficult to find a rule that can be found for any number of values n+1 (in the upper left corner is 0, 0 coordinates):
x = 2 + n + n/3;
y = 1 + n-n/3;

In fact, this rule can be simply extended to any odd-numbered magic square (the following size is odd):
x = size/2 + 1 + n + n/size; (Note that the division here is the divide method, without decimals)
y = size/2 + n-n/size;

In this way, we can put the original complex cycle, reduced to a simple cycle of

Then there is the procedure:
View plain Copy to clipboard print? #include  <stdio.h>    #define &NBSP;SIZE&NBSP;5&NBSP;//defines the magic square order, which can only be an odd number    int  Main ()    {   int x, y, i, sqsize, hsize;   int sqMap[ size][size];   sqsize = size * size;   hSize = SIZE /  2;  //Calculate the position of the number 1 to size * size and record    for  ( i = 0; i  < sqsize; i++)    {   x = hsize + 1 + i  + i / SIZE;   y = hsize + i - i / size;    sqmap[y % size][x % size] = i + 1;  }   //Below is output    for  (y = 0; y < size; y++)    {    for  (x = 0; x < size; x++)    printf ("%4d",  sqmap[y][x]);   puts ("");  }   return 0;  }    #include <stdio.h> #define SIZE 5//define Magic Order number, this number can only be odd int main () {int x, y, I, sqsize, hsize int sqmap[ Size][size]; sqsize = size * size; Hsize = SIZE/2; Calculates the position of number 1 to size * and records for (i = 0; i < sqsize; i++) {x = hsize + 1 + i + i/size; y = hsize + i-i/SIZE; sqmap [Y% SIZE] [x% SIZE] = i + 1; //Below is output for (y = 0; y < size; y++) {for (x = 0; x < SIZE; x +) printf ("%4d", Sqmap[y][x]); puts ("");} return 0; }
It's a lot shorter than the number of odd-numbered magic squares You can find on the web (but more on the web as a magic square, somehow).



4. String Rotation shift

Question, give you a string that requires the loop to move left n bit
For example, to the "ABCDEFG" loop left 2, we want to get "Cdefgab"

Attach conditions, you cannot use contiguous secondary space (including dynamic allocation), you can use only a few individual variables (that is, O (1) space)

First, we know that reversing a string operation ("ABCD" to "DCBA") does not require an extra array of auxiliary, as long as the data is exchanged on the tail.

However, you may not know that string rotation can be achieved simply by using string inversion:


View plain Copy to clipboard print? Reverses the string, reversing the contents of the middle that the St and Ed Point to (including St does not contain ed) void Str_rev (char* St, char *ed) {for (--ed; St < Ed; ++st,--ed) {ch   AR c; c = *st; *st = *ed;   *ed = C; }//reverse string, reverse the contents of the middle that St and Ed Point to (contains St does not contain ed) void Str_rev (char* St, char *ed) {for (--ed; St < Ed; ++st,--ed) {Char C c = *st; *st = *ed; *ed = C; } }
View plain Copy to clipboard print? Three evils to the equivalent left-shift string (between St and Ed, contains St does not contain Ed content)    CHAR*&NBSP;STR_SHL (char* st, char* ed, int  n)    {   Str_rev (st, &st[n]);   Str_rev ( &st[n], ed);    Str_rev (st, ed);   return st;  }  //Three evils equivalent left-shift string (between St and Ed, Contains St content that does not contain ed) char* Str_shl (char* St, char* ed, int n) {Str_rev (St, &st[n]); Str_rev (&st[n), ed); Str_rev (St, Ed ); Return St; View plain Copy to clipboard print? #include  <stdio.h>    #include  <string.h>    int main ()    {   char str[] =  "abcdefghijklmnopqrstuvwxyz";   puts (str,  str + strlen (str),  6)  );   GetChar ();   return 0;   }   #include <stdio.h> #include <string.h> int main () {char str[] = "abcdefghijklmnopqrstuvwxyz"; Puts (STR_SHL (str, str + strlen (str), 6)); GetChar (); return 0; }
Here, if you want to loop left n bit, just divide the original string into two paragraphs, the first n characters, and the other characters behind

The two sections are reversed, and then the whole is reversed, and the loop is moved to the left (if the whole and then two parts, the loop right)

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.