Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Math Formula in Variable

Tags:

javascript

My script can print a pattern of triangular numbers (e.g. 1, 3, 6, 10,...), but I want to store the formula (n * (n + 1)) / 2 in a variable called formula instead of writing it multiple times in the if-else statement.

/* Current script */

var pat = document.getElementById("pattern");
var nMax = 10; // max number of intervals

for (var n = 1; n <= nMax; ++n) {
    if (n != nMax)
        // insert comma and space after each interval
    	pat.innerHTML += (n * (n + 1)) / 2 + ", ";
    else
        // append ellipsis after last interval
        pat.innerHTML += (n * (n + 1)) / 2 + ",&hellip;";
}
<body>
    <p id="pattern"></p> 
</body>

Here is what I tried already but ended up with 1, 1, 1, 1, 1...:

I moved var n = 1 to its own line under the nMax variable so that n is defined in the formula and changed the first part of the for loop to n = 1. Then in the if-else statement, I replaced every instance of (n * (n + 1)) / 2 with the formula variable. After testing the modified script, the pattern resulted in all 1s.

/* Version with formula variable (not working properly) */

var pat = document.getElementById("pattern");
var nMax = 10; // max number of intervals
var n = 1;

var formula = (n * (n + 1)) / 2;

for (n = 1; n <= nMax; ++n) {
    if (n != nMax)
    // insert comma and space after each interval
      pat.innerHTML += formula + ", ";
    else
    // append ellipsis after last interval
      pat.innerHTML += formula + ",&hellip;";
}
<body>
    <p id="pattern"></p> 
</body>

How could I store the formula in a variable and use it without getting unexpected results?

like image 750
Jon Kantner Avatar asked Dec 03 '22 16:12

Jon Kantner


1 Answers

Put the formula in a function:

function formula(n) { return n * (n + 1) / 2; }

Then you can call it :

pat.innerHTML = formula(n) + ", ";
like image 154
Pointy Avatar answered Dec 05 '22 06:12

Pointy