Home > Web Front-end > JS Tutorial > JS implements the sum of numbers within 1000 that is divisible by 3 or 5_javascript skills

JS implements the sum of numbers within 1000 that is divisible by 3 or 5_javascript skills

WBOY
Release: 2016-05-16 15:14:46
Original
2101 people have browsed it

Today I saw a question like this in the technical group: Find the sum of numbers within 1000 that are divisible by 3 or 5. Among them, I saw the very interesting solution 2. I was quite confused at first, but after thinking about it for a while and receiving some advice, I felt enlightened.

The first solution is very common, which is to go through all the numbers within 1000. As long as there are numbers that are divisible by 3 or 5, add them up and finally get a total sum.

What interests me is the second solution, which cleverly uses the mathematical arithmetic sequence

The series of the first term of an arithmetic sequence with tolerance is:

The second method uses (a1+an)/3*3 in the first step, so it becomes 3*(1+333)*333/2. This step is to divide all the terms by 3 Add it up.

Similarly, in sum(Math.floor(input-1)/5))*5, add up all the items within 1000 that can be divided by 5. Finally, there are repeated numbers that can be divided by 3 and 5. , such as 15, then subtract the numbers that are repeatedly divided by 15, and you can get the sum of numbers within 1000 that can be divided by 3 or 5.

This is the end of the introduction to the JS implementation of finding the sum of numbers within 1000 that is divisible by 3 or 5. I hope it will be helpful to you!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template