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

Asked

Viewed 1,231 times

3

I have a question, I need to do a function in Javascript that shows the 50 numbers that the sum of their digits is equal to 10, example:

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.

I was able, at first, to calculate the digits of the number, using a form, I just couldn’t develop the 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;   
}
  • I didn’t understand how your current code works (which is the input?), nor where is the problem... Could [Edit] the question including more details?

  • From what he implied, he has no idea how to construct the logic to display this list with 50 nums

  • the input is in a form, the variable x is coming from an input, in this case, I’m typing a number in a form, example: 26, and it’s giving me the sum of the digits, 2+6 =8, but Nan has already answered the question, thanks

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 this is over, just display the contents of numeros somewhere. You can transform the content of this Array in a string using numeros.join(", "), for example.

BTW for evidence, the result should be:

[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 laces. The cat jump here is the key word while ;)

  • I was working on a very similar brute-force solution: http://jsfiddle.net/63uhw/

  • 1

    That’s what I really wanted, thanks for the answer! I’ll understand the logic that Oce used for the next exercises

4

Although the answers already solve the problem, I will leave an option using only one 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

  • I became your fan! + 1

  • Thanks, I wrote down here the codes for future use and understanding!

  • 1

    +1 Only one add-on: initially it is not necessary to separate the string with .split(""), because a Javascript string is equivalent to an array in which each element is a 1-character string. It is not possible to do i.toString().reduce because String does not inherit from Array, but it can be done Array.prototype.reduce.call(i.toString(), ... (or simply [].reduce.call(i.toString(), ...).

  • @mgibsonbr interesting, thank you I will use so.

3

Although Renan’s response makes the main task, if your difficulty is in integrating 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 facilitate the understanding, but obviously the code can be restructured in a more professional way, like Renan’s. Also I 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 must be equal to 10".

I hope it helps.

  • input was a test I was doing with the code, to see if really split and Join were adding up the digits. As it was a short time ago that I started to do javascript, I do input tests and then apply the logic. Thanks for the answer!

  • Oops! Ah, I got it, I thought that was the final code, so the comment on top of "x++" and getElementById :D Renan’s answer is cleaner and more usable, then! No reason, hugs, hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.