Function that writes the first 50 numbers whose sum of digits is 10

3

I have a question, I need to make a function in JavaScript that shows the 50 numbers that the sum of their digits equals 10, eg:

Number 19, digits 1 and 9, sum of digits: 1 + 9 = 10. The function should show me the number 19, showing a total of 50 numbers.

At first I was able to calculate the digits of the number using a form , I just could not develop logic to show the 50 numbers.

function start()  {
    var form = document.getElementById("exercicio_8");
        var x = form.num_5.value;
        var y = x.toString().split("");
        var soma = eval(y.join('+'));
        document.getElementById("saida2").innerHTML = soma;   
}
    
asked by anonymous 20.05.2014 / 20:05

3 answers

8

I imagine something like:

var numeros = [];
var contador = 0;
while (numeros.length < 50) {
    var acumulador = 0;
    var algarismos = (contador + "").split("");
    for (var i = 0; i < algarismos.length; i++) {
        acumulador += parseInt(algarismos[i]);
    }
    if (acumulador === 10) {
        numeros.push(contador);
    }
    contador++;
}

When that's over, just display the contents of numeros somewhere. You can transform the contents of this Array into a string using numeros.join(", ") , for example.

BTW for proof purposes, the result should be this:

[19, 28, 37, 46, 55, 64, 73, 82, 91, 109,
 118, 127, 136, 145, 154, 163, 172, 181,
 190, 208, 217, 226, 235, 244, 253, 262,
 271, 280, 307, 316, 325, 334, 343, 352,
 361, 370, 406, 415, 424, 433, 442, 451,
 460, 505, 514, 523, 532, 541, 550, 604]

editing : After rereading the question, I think your problem is with ties. The cat's leap here is the keyword while ;)

    
20.05.2014 / 20:20
4

Although the answers already resolve the problem, I'll leave an option using only loop and array.reduce () :

 var numeros = []; // para armazenar os números
 // sabemos que o primeiro número é 19, portanto loop inicia em 19
 for (var i = 19; numeros.length < 50 ;i++){ 
    //separa os algarismos
    var alg = i.toString().split("");
    // reduce aplica uma função em cada valor do array da esquerda para direita 
    var sum = alg.reduce(function(a,b){
       return parseInt(a) + parseInt(b);
    });
    // if else ternário, adiciona ao array se atender a condição
    sum == 10 && numeros.push(i); 
 }
 //imprime os números no body separados por vírgula
 document.body.innerHTML = numeros.join(', ');

JSFiddle Example

    
20.05.2014 / 22:27
3

Although Renan's answer does the main task, if your difficulty is to integrate with what you already have, this code should be easier for you to adapt:

    function start()  {
        var cont = 0;
        var x = 1;
        do {
            // Aproveitando uma parte do seu código:
            var y = x.toString().split("");
            var soma = eval(y.join('+'));

            // Algumas alterações daqui pra baixo:
            if(soma == 10){
                document.getElementById("saida2").innerHTML += ", " + x;
                cont++;
            }
            // x precisa ser iterado, e não entrado pelo usuário:
            x++;
        } while(cont < 50);

        // Ajuste final: precisamos remover a vírgula sobrando no começo:
        document.getElementById("saida2").innerHTML = document.getElementById("saida2").innerHTML.substr(2);
        // Comente a linha acima para entender o que eu estou falando!
    }

I tried to make it easier to understand, but obviously the code can be restructured in a more professional way, like Renan's. I also do not understand the reason for your input, I believe you want to print the first 50 numbers that meet the condition: "The sum of the digits should be equal to 10."

I hope it helps.

    
20.05.2014 / 21:07