


Summary of common algorithms such as JS accumulation, iteration, exhaustion, and recursion
This time I will bring you a summary of the use of common algorithms such as JS accumulation, iteration, exhaustion, and recursion. What are the precautions for the use of common algorithms such as JS accumulation, iteration, exhaustion, and recursion, as follows. This is a practical case, let’s take a look at it.
Accumulation and accumulation
Accumulation: Add a series of data to a variable. The final cumulative result is obtained
For example: Calculate the cumulative sum of the numbers from 1 to 100
The ball falls from a height and returns to half of the original value each time. Find the tenth time the ball lands. The distance traveled by the ball in time
<script> var h=100; var s=0; for(var i=0;i<10;i++){ h=h/2; s+=h; } s=s*2+100; </script>
Accumulation:Multiply a series of data into a variable to get the cumulative result.
The common one is the factorial of n
var n=100; var result= 1; for(var i=1;i<p style="text-align: left;">General form: </p><p style="text-align: left;">Accumulation: V =e;</p><p style="text-align: left;">Accumulation: v*=e;</p> <p style="text-align: left;">V represents accumulation and accumulation, e represents accumulation/accumulation term</p><p style="text-align: left;"><strong>Key points of the algorithm: </strong></p><p style="text-align: left;">(1) Initialization</p><p style="text-align: left;">Initialize v and e</p><p style="text-align: left;">Accumulation: v = 0; </p><p style="text-align: left;">Accumulation: v = 1; </p><p style="text-align: left;">e initialization, if the accumulation/product item is complex, it may be decomposed into several sub-items and initialized separately , such as the problem of calculating pi, the cumulative term is decomposed into three parts: symbol, numerator and denominator. </p><p style="text-align: left;">(2) Loop control conditions</p><p style="text-align: left;">One is a fixed number of times, such as the problem of calculating the bounce distance, the problem of calculating the sum of the first 20 items of the sequence, </p><p style="text-align: left;">number of times It is not fixed, but must meet a certain condition: the problem of calculating pi requires that the absolute value of the last term be less than 10-6. </p><p style="text-align: left;">(3) Determine the change of the accumulation/product term</p><p style="text-align: left;">For example, the sum of the first 20 terms of a sequence is to use the sum of the current numerator and denominator as the next denominator, and the current denominator as the numerator . </p><p style="text-align: left;">Another example is the problem of finding pi, which is to invert the sign, add 2 to the denominator, and then find the next term. </p><p style="text-align: left;"><span style="font-size: medium"><strong>Iteration</strong></span></p><p style="text-align: left;"><strong>The iteration method is also the rolling method</strong></p><p style="text-align: left;">Rule: it can be used continuously The old value gets the new value until we get the result we want. </p><p style="text-align: left;">How to solve the problem of iteration</p><p style="text-align: left;">1. Find the iteration variable (old value)</p><p style="text-align: left;">2. Determine the relationship between iteration</p><p style="text-align: left;">3. Knowing what the desired result is (conditions for ending the loop) </p><p style="text-align: left;"> (1) is to know the final result </p><p style="text-align: left;"> (2) The number of loops </p><pre class="brush:php;toolbar:false"><script> /* * 1.接受用户输入的俩个数 * 2.一个函数的到最大公约数 * 3.打印这个最大公约数*/ var num1 = Number(prompt("请输入一个数")); var num2 = Number(prompt("请输入一个数")); var result = GCD(num1,num2); alert(result); /* * 函数的功能:得到最大公约数 * 函数名:GCD * 函数的参数:俩个整数 * 返回值:最大公约数*/ /* * 如果num1<num2则交换,确保num1是交大的 * 计算余数 * 当num1(除数),对num2(被除数)的余数不为0,重复一下步骤 * num2=>num1, * 余数=>num2 * 重新计算余数 * 最终的到最大公约数,也就是num2的值*/ function GCD(num1,num2){ /*return0;*/ if(num1<num2){ var t = num1; num1=num2; num2 = t; } var remainder = num1%num2; while(remainder!= 0){ num1=num2; num2= remainder; remainder=num1%num2; } returnnum2; } </script>
Recursion
Find the mathematical rule: calculate the value of the next item through the formula until the result we want
For example: a rabbit gives birth: through the first two The item gets the next item
<script> /* * 一般而言,兔子在出生俩个月后,就有繁殖能力 * 一对兔子每个月能生出一对小兔子来 * 如果所有的兔子都不死,那么一年以后总共有多少对兔子*/ /* * 月份 0 1 2 3 4 5 6 * 幼崽 1 1 1 2 3 5 8 * 成年 0 0 1 1 2 3 5 * 总共 1 1 2 3 5 8 13 * */ /* * 接收用户输入的月份 * 计算兔子的对数 * (1)如果经过的月份<2那么兔子的对数为1 * (2)否则用初始的兔子的对数 加上 第一个月的对数为 * 第二个月兔子的个数(an = an-1 +an-2) * 反复使用这个公式,计算出下个月兔子的个数一直到用户输入的月份为止 * 打印的兔子的对数 * */ /* var month = Number(prompt("输入月份")); var sum ; var an =1; var an_1=1; var an_2; if(month < 2){ sum=1; }else{ sum=2; for(var i=1; i<month; i++){ sum= an +an_1; an_1 =an; an = sum; } } alert(sum);*/ /* * 思路2*/ var month = Number(prompt("输入月份")); var rabbit = [1,1]; for(var m=2;m<=month;m++){ rabbit[m]=rabbit[m-1]+rabbit[m-2]; } alert(rabbit[month]); </script>
Recursion is divided into forward push and reverse push.
Exhaustion
When you encounter a problem and can’t find a better solution (can’t find a mathematical formula or rule) , use the "stupidest" method, take advantage of the fast computing speed of computers, list all possibilities
and record the results we want
<script> /* * 公鸡一值钱5,鸡母一值钱三,鸡仔三值钱一 * 百钱买百鸡,问公鸡,鸡母、鸡仔各几何? * x y z * x + y + z = 100 * x*5 + y * 3 + z/3 = 100*/ for(var cock=0;cock<=20;cock++){ for(var hen=0;hen<=33;hen++){ var chihen=100-cock-hen; if(100== cock*5+ hen*3+ chihen/3){ document.write("公鸡一共:"+cock+"鸡母一共:"+hen+"小鸡一共:"+chihen+"<br>") } } } </script>
Exhaustive method Its characteristics are: the algorithm is simple and the corresponding program is also simple, but the amount of calculation is often large. However, the advantage of computers is their fast computing speed, so this algorithm can maximize its strengths and avoid weaknesses, and can often achieve good results.
Case: There is a three-digit number, the ones digit is larger than the hundreds digit, and the hundreds digit is larger than the tens digit, and the sum of the digits is equal to the product of the multiplication of the digits, find these three Number of digits
Recursion
The so-called recursion is to call yourself again inside the function.
For example, to find the factorial problem, the fact function is called inside the fact function
<script> /*计算n的阶乘*/ function fact(n){ if(1== n){ return 1 } return n*fact(n-1); } alert(fact(5)); </script>
The recursive algorithm is very complicated to understand according to the conventional thinking, and the function calls are nested layer by layer. Call, and then return layer by layer, you might as well change your mind to understand recursion.
Recursion is actually solving a problem of size n by reducing it to a problem of n-1. That is to find the relationship between n and n-1.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Summary of common JS algorithm examples
##Detailed explanation of JavaScript callback function use cases
The above is the detailed content of Summary of common algorithms such as JS accumulation, iteration, exhaustion, and recursion. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
