When solving the problem of picking eggs, we realized the importance of algorithm and programming optimization by comparing the speed of several shell scripts.

Source: Internet
Author: User

A few days ago, a classmate in the group to raise an egg problem, the original question is as follows:

There was a basket of eggs,

One 1, just take it out.

2, 2, take it, just finish it.

3, 3, take it, just finish it.

4 of 4, 2 left.

5 of 5, 4 left.

6, 6, take it, just finish it.

7 of 7, 5 left.

8 of 8, 2 left.

9, 9, take it, just finish it.

How many eggs are there in the basket, please?

Please use the script method to calculate the total number of eggs!


Personally feel this topic is not rigorous, because at least I did not see, the question is "How many eggs in this basket?" "or" the total number of eggs in a basket within a certain range (such as the basket can be up to 100,000 eggs in the premise of the condition), to find the basket of eggs may be how many? "Let's take the first guess to answer the question, and the second guess is to expand it for a variant," he said.


In fact, this problem seems to be more common, in the online casually can search the answer, but without thinking to get to use do not understand digestion into their knowledge, the next encounter the same or similar problems will not, coupled with the teacher of the training course this time is also talking about Shell advanced programming, Take this topic to practice shell programming.


The first thing to think about is a simple brute force-cracked script: one count, one count! What's so hard about that?

Code 1 (Simple rough version):

#!/bin/bashecho-e "There is a basket of eggs, \n1 a 1 take, just take the \n2 2 take, just take the \n3 3 take, just take the \N4 4 take, the remaining 2 \n5 5 take, the remaining 4 \n6 6 take, just take the \n7 7 take, the remaining 5 \ N8 A 8 take, the remaining 2 \n9 9 take, just take out \ n Beg: How many eggs in the basket? \ n Please use the script method to calculate the total number of eggs! \ n "For I in {1..100000}do if [[$i%1-eq 0]] && [[$i%2-eq 0]] && [[$i%3-eq 0]] && [[$i%4  -eq 2]] && [[$i%5-eq 4]] && [[$i%6-eq 0] && [[$i%7-eq 5] && [[$i%8-eq 2]] && [[$i%9-eq 0] then echo $i break Fidone

By the way, use the time command to test how long the script runs:

First time:

Second time:

Third time:

Test pass, no problem, but this code is written too brain-free, can not bear to look straight, there is no optimization of space it? The answer is yes, but it takes a little bit of logical thinking (learning Math in elementary school).


Think about how to optimize:

1. Any number can be divisible by 1, this does not need to be judged.

2. Can be divided into 2, 3, 6, 9 at the same time, then because 2, 3, 6, 9 of the least common multiple is 18, so directly with a multiple of 18 to determine whether 4 more than 2, in addition to 5 4, in addition to 7 5, in addition to 8 2 can be, here a little need to pay attention to is not except

3. Hidden conditions: 5 5 to take, leaving four, then the total number of eggs in the basket is either 4 or 9, but by the condition 2 (2 2 Take, just take out), this number must be even, so the single digit can not be 9. Combining this number must be a multiple of 18 this condition, then when this number is 18 3+5xn times, you can simultaneously satisfy both the "multiples of 18" and "single digit is 4" two conditions.

After thinking, we began to study how to cycle 18 3+5xn times can be more than 4 2, in addition to more than 7 5, in addition to more than 8 2

Code 2 (optimized version):

#!/bin/bash############################################################### File name:modified.sh# version:v1.0# Author:damon pan# blog:http://blog.51cto.com/oldpan# Created time:2018-04-17 15:00:28# description:null############# ################################################ #echo-E "There is a basket of eggs, \n1 1 take, just take the \n2 2 take, just take \n3 3 take, just take \n4 4 take, the remaining 2 \n5 a 5 take, the remaining 4 \n6 6 take, just take the \n7 7 take, the remaining 5 \n8 8 take, the remaining 2 \n9 9 take, just take out \ n Beg: How many eggs in the basket? \ n Please use the script method to calculate the total number of eggs! \ n "for ((i=0;i<=100000;i++)) does ((N=18* (3+5*${i}))) if ((${n}%4==2)) && ((${n}%7==5)) && ((${n}%8==2 ) then echo ${n} break Fidone


Also use the time command to test how long the script runs:

First time:

Second time:

Third time:


There is no comparison, there is no harm! 30 times more speed difference! This is just a case of counting to 1314 and stopping. So what if we change the subject's requirements? For example, as I did in the previous article on the question of the requirements of the second speculation, the title of the request to: "If the basket can be loaded up to 100,000 eggs, the basket may have a number of eggs." ”


The simple brute code is to remove the break from the If loop in the code 1 simple rough version of the previous article, where the code is not repeated, and only the results of the three time run script are listed below.

Time Test First:

Second time:

Third time:


So how fast is the optimized script running? (The Code section also simply removes the break from the If loop in the Code 2 optimization version of the previous article, but the test below proves that it actually made a logical mistake)

Time Test:

This ~ ~ How much more time than the script without optimization? And the figure is over 100,000. The code must be wrong, start modifying the code

If a condition is added to the If judgment, N cannot be greater than 100,000, so the output is correct after the modification, but the script execution is still slow.

Time Test First:

Second time:

Third time:


It seems that the code is still a problem, looking back at the code carefully, and found that although a judgment in the IF, but in fact, the number of operations for the loop is not reduced once, but the calculation will no longer show the results after 100,000. continue to modify the code:


#!/bin/bash############################################################### File name:finalversion.sh# Version: v1.0# Author:damon pan# blog:http://blog.51cto.com/oldpan# Created time:2018-04-17 16:06:27# description:null######## ##################################################### #echo-E "There is a basket of eggs, \n1 a 1 take, just take the \n2 2 take, just take \n3 3 take, just take \n4 4 take , the remaining 2 \n5 a 5 take, the remaining 4 \n6 6 take, just take the \n7 7 take, the remaining 5 \n8 8 take, the remaining 2 \n9 9 take, just take out \ n Beg: How many eggs in the basket? \ n Please use the script method to calculate the total number of eggs!  \ n "for ((i=0;i<=100000;i++)) does ((N=18* (3+5*${i})) if ((${n}>100000)) Then break elif ((${n}%4==2)) && ((${n}%7==5)) && (${n}%8==2) then echo ${n} fidone


Time Test First:

Second time:

Third time:


The efficiency of the calculation increased more than 40 times, not as large as expected, maybe my program logic is still a problem, there should be further optimization of the improvement of the place. But because of my math and programming level is extremely limited, and then change the change is not moving ... Also hope to have a master generous enlighten, in the next first thanked!


This test through the classmate raised a problem, verify the importance of algorithm and programming optimization, just use a most simple low-level optimization, then the calculation efficiency increased by about 40 times times, if the need to calculate the amount of data is very large, the increase in efficiency is very obvious.

When solving the problem of picking eggs, we realized the importance of algorithm and programming optimization by comparing the speed of several shell scripts.

Related Article

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.