-1

//This program calculates how many times a number is divisible by 2.

//This is the number and the amount of times its been split into 2.

    let Num=64
    let divisible=0

//This is the ternary operator, it basically asks a question.

    Num % 2 === 0 ?
    divisible=divisible++ : document.write(divisible);

    Num/=2;

    Num % 2 === 0 ?
    divisible=divisible++ : document.write(divisible);

    num/=2

    Num % 2 === 0 ?
    divisible=divisible++ : document.write(divisible);

//Once the statement evaluates to false it writes the amount of times the number has been divided by 2 into the document.

  • Because 64 is divisible by 2 more than just 3 times, so this never prints anything? – Bergi May 11 '20 at 16:34
  • 64, 32, 16 are all divisible by 2. Although `num != Num` so it's just checking whether 64 and 32 are divisible by 2 and the `document.write` branches never fire. The program doesn't make sense. – ggorlen May 11 '20 at 16:34
  • 1
    Also, [don't use `document.write`](https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – Bergi May 11 '20 at 16:35
  • 1
    Why not attempt to solve your assignment by yourself first? – connexo May 11 '20 at 16:35
  • 1
    Btw, using a ternary operator here is not a good practice. `if`/`else` would be more appropriate. – Bergi May 11 '20 at 16:35

3 Answers3

1

You could try it with a loop.

let num=64;
let divisible=0;
while(num % 2 === 0) {
    num /= 2;
    divisible++;
}
console.log(divisible);
document.write(divisible);
koalabruder
  • 2,582
  • 7
  • 29
  • 36
1

There are several issues with this code. Some of the comments have pointed out the looping concerns. However, one that stands out that won't be addressed with a loop is your misuse of the post-fix increment operator, ++. This operator returns the value and then increments the value, so divisible = divisible++ will result in divisible remaining unchanged. Based on your intent, all you need to do is divisible++.

Try the following:

while(true){
    if(Num % 2 === 0){
        divisible++; 
        Num /=2;
    }
    else{
        document.write(divisible); 
        break;
    } 
}
Philip Wrage
  • 1,219
  • 1
  • 7
  • 18
0

Here as per example given for 64 and no looping is provided , it will never go to document.write(divisible) statement in 3 step provided above . That's why nothing getting printed .

Moreover , divisible=divisible++ doesn't make any sense . Here , since it is postfix operartor , first value will be assigned then it will be incremented so value of divisible will be 0 only .

Num % 2 === 0 ?divisible++ : document.write(divisible); 

And , as per my understanding document.write accepts string parameter but here divisible is of number type .