⊗jsSpOptOA 275 of 294 menu

Choosing an optimal algorithm in JavaScript

Sometimes a code problem arises due to the fact that not the most optimal solution to the problem is chosen.

Let, for example, we are faced with the task of finding the sum of integers from 1 to 1000000. Let's solve the problem:

let sum = 0; for (let i = 1; i <= 1000000; i++) { sum += i; } console.log(sum);

What is wrong? The fact is that to solve the problem, there is a math solution.

This solution requires almost no resources! Let's program it:

let n = 1000000; let sum = n * (n + 1) / 2; console.log(sum);

Moral: before solving a resource-intensive task, be sure to check if there is a ready-made math formula or ready-made math approach for solving it.

Find the number of numbers from 1 to 1000 divisible without remainder by 5 .

Find the number of digits needed to write down all the numbers from 1 to 1000000.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline