HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Finding the sum of all the multiples of 3 or 5 below any given number

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thenumberallanyfindingmultiplesbelowsumgiven

Problem

I wrote the following simple function in JavaScript that finds the sum of all the multiples of 3 or 5 below a value, given from a text-box.

I have used \$\dfrac{n}{2(a_1 + a_n)}\$ (sum of arithmetic sequence).

I was wondering if there is a way to shorten or otherwise improve this code.

function sum_of_all_mul_3_5(){
    var value=parseInt(document.getElementById("input").value);
    var result=(((Math.floor((value-1)/3))*(3+((Math.floor((value-1)/3))*3)))/2)+(((Math.floor((value-1)/5))*(5+((Math.floor((value-1)/5))*5)))/2)-(((Math.floor((value-1)/15))*(15+((Math.floor((value-1)/15))*15)))/2);
    document.getElementById("output").value=result ;
    }

Solution

I'm going to take by "shorten", you mean "remove this duplication", in which case the answer is yes. Extract an SumSequence function. Give things some breathing space while you're at it.

function sum_of_all_mul_3_5(){
    var value=parseInt(document.getElementById("input").value);
    var result=sumSequence(value, 3) + sumSequence(value, 5) - sumSequence(value, 15);
    document.getElementById("output").value=result ;
    }

function sumSequence(value, x){
    return (Math.floor((value - 1) / x) * (x + ((Math.floor(value - 1) / x) * x))) / 2);
    }


For the record though, using the arithmetic sum of the sequence is a very elegant solution to this problem though. I know of no more efficient way to do it, but a comment explaining what's going on here would be beneficial to any future maintainer. You might even want to go the extra mile and drop a link to wikipedia in that comment.

Code Snippets

function sum_of_all_mul_3_5(){
    var value=parseInt(document.getElementById("input").value);
    var result=sumSequence(value, 3) + sumSequence(value, 5) - sumSequence(value, 15);
    document.getElementById("output").value=result ;
    }

function sumSequence(value, x){
    return (Math.floor((value - 1) / x) * (x + ((Math.floor(value - 1) / x) * x))) / 2);
    }

Context

StackExchange Code Review Q#94539, answer score: 5

Revisions (0)

No revisions yet.