5
\$\begingroup\$

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 ;
    }
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Well mainly I tried to avoid loops in this,and yes I know my code is not in code standards but that's why I started to put code in here . To learn how to do it properly ,not be just shorten \$\endgroup\$
    – menaka
    Jun 24, 2015 at 12:17

2 Answers 2

5
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

I suggest dividing calculation and Input/Output:

function sum_of_all_mul_3_5(limit){
    return sumSequence(value, 3) + sumSequence(value, 5) - sumSequence(value, 15);
    }

You can then use it in different ways such as:

alert(sum_of_all_mul_3_5(prompt("Max: ")))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.