Ganoss_
Ganoss_

Reputation: 13

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);

Upvotes: 0

Views: 303

Answers (2)

Jordan Messfeldt
Jordan Messfeldt

Reputation: 1

Do all n positive integer values return to integer 1 for the following system of complex equation:

5n +1 if n=odd
n/2 if n=even
Not all n positive integers return to 1, only the values represented return to 1.
For the 5+1 complex system under the odd and even conditions above, this image

Upvotes: 0

Jamiec
Jamiec

Reputation: 136239

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
}

Upvotes: 0

Related Questions