Code efficiency from Gaussian number

zhaozj2021-02-16  53

Many of the program-speaking books said that the high-speed and code of the algorithm is often uncomfortable; especially in the current hardware environment (high-speed CPU and large-capacity hard drive), it doesn't matter if the algorithm is both the fastest. It is also the shortest, in general, can reach one of them. However, I think that in some cases, fish and bear palms can be both - just do a little "hand feet" in the algorithm. Here I will use a simple example to talk about this problem, but my premise is that I will never use the spaghetti algorithm, even if I get an efficient code. Example: Seeking 1 2 3 ... 100. Solution 1: Use the for loop (with C to implement algorithm, the same below). #include void main () {INT I, SUM = 0; for (i = 1; i <= 100; i ) SUM = I; cout << "sum =" << Sum << endl; Return;} Solution 2: Use recursive. #include int getSum (int); void main () {int sum = getsum (100); cout << "sum =" << sum << endl; return;} int getsum (int x); {IF (x == 1) RETURN (1); Else Return (X GetSum (X-1));} It is obvious that the above two algorithms are less efficient, because there is too much in recursion. System resources. The efficiency of solving 1 is really high, but I want to tell you that it is not the highest efficiency! Now please look at my code, it is the inspiration I got from an entry-level textbook: #include void main () {int sum = (1 100) * 100/2; cout << " Sum = "<< Sum << endl; return;} Yes, this is Gaussian evaluation formula. But you read such a "algorithm", maybe very uncomfortable, tell me: This can't be counted as a good algorithm because it does not reflect the superiority of the computer. That's right, you are right, the example of this textbook is also an example, and does not advocate such programming, the reason is as you said. However, no matter what you are happy, you must admit: This code is legal, and it is not spaghetti, readability is also very strong; the most important point is that it is very efficient - it does not do 100 cycles Only three steps were done, but also saved a storage unit of a variable (I). Textbooks are teaching materials and programming is programming. The purpose of the textbook is to let you design how to make a computer more work algorithms, and you can even even don't even know how to make the computer, just let the computer are not annoying 100 times; the purpose of programming is to be as efficient algorithms Get the correct answer, don't have to use a cycle or a Gaussian formula.

转载请注明原文地址:https://www.9cbs.com/read-26118.html

New Post(0)