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!