javascriptdomcollatz

Collatz conjecture


I am trying to make the Collatz conjecture in JS but I have a problem and I do not understand it. When I click on the button it return me 0, can someone help me please?

My js code:

let input   = document.getElementById('nombre');
let btn     = document.getElementById('submit');
let output  = document.getElementById('output');
let coups;

let nombre = input.value;

function conjecture() {
    do {
        if (nombre%2 === 0) {
            nombre /= 2;
            output.innerHTML += nombre + '<br>';
            coups ++;
        } else {
            nombre *= 3;
            nombre ++;
            output.innerHTML += nombre + '<br>';
            coups++;   
        }
    } while (nombre>1);

    output.innerHtml += `La courbe a atterit en ${coups} coups.<br>`; 
}

btn.addEventListener('click', conjecture);

Solution

  • You are reading the value before the user has had a chance to enter a number.

    let nombre = input.value;
    

    Make sure that line is inside your method which is called on click

    function conjecture() {
         let nombre = input.value;
         ... rest of your code
    }