How to find sum of all permutations of a whole number?

3.71K viewsProgramming
0

Can the reader give the sum of all the whole numbers that can be formed with the four figures 1, 2, 3, 4? That is, the addition of all such numbers as 1,234,1,423,4,312, etc. You can, of course, write them all out and make the addition, but the interest lies in finding a very simple rule for the sum of all the numbers that can be made with four different digits selected in every possible way, but zero excluded ?

Changed status to publish
0

There are 2 ways to do this:-
One is to devise a formula for this and the other one is to loop through and find all permutations of  all 1,2,…n digit/s whole numbers and sum them together.

<div id="result">
</div>


init();
  function init() {
    document.getElementById('result').innerHTML = "<h2>All permutations : <br/>";
     var num = '1234',
        length = num.length,
        permute_sum = 0,
        sum1 = permuteAndCalcSum('', num, permute_sum),
        sum2 = calcSumFormula(length);
       document.getElementById('result').innerHTML += "</br>Sum obtained by brute force : " + sum1 + "<br/>Sum obtained from formula : " + sum2;
     if (sum1 === sum2) {
        document.getElementById('result').innerHTML += "<br/>Both sums match</h2>";
    } else {
        document.getElementById('result').innerHTML += "<br/>Sums don't match</h2>";
    }
  }
 function calcSumFormula(length) {
    var formula_sum = 0;
    for (var i = length - 1; i >= 0; i--) {
        formula_sum += Math.pow(10, i);
    }
     formula_sum = (length * (length + 1) / 2) * formula_sum * factorial(length - 1);
     return formula_sum;
}
 function factorial(n) {
    if (n === 0)
        return 1;
    else return n * factorial(n - 1);
}
   function permuteAndCalcSum(prefix, string, permute_sum) {
    var n = string.length;
    if (n === 0) {
        permute_sum += parseInt(prefix);
        document.getElementById('result').innerHTML += prefix + "<br/>";
        return permute_sum;
    } else {
        for (var index = 0; index < n; index++) {
            permute_sum = permuteAndCalcSum(prefix.concat(string[index]),
                string.slice(0, index).concat(string.slice(index + 1, n)), permute_sum);
        }
    }
    return permute_sum;
}

Changed status to publish
You are viewing 1 out of 1 answers, click here to view all answers.
Write your answer.

Categories