#using collatz conjecture

18 messages · Page 1 of 1 (latest)

vivid swan
#

My homework assignment is to use the collatz conjecture and use a loop until I get 1. I need to output each number and the number of steps taken to get to 1. I can't figure out how to do both of those, and when I input a number, it is only halved and won't continue to 1.

#

for example when I input 20, my watcher only shows 10 and nothing shows up in my text area

half tundra
#

What is hailstone?

#

Does num ever change?

vivid swan
#

Hailstone is just a var name

#

and num is the number inputted so it changes when the person changes it?

#

I think this is like javascript but not

nimble glen
#

try console log your variables at each step so u can see if anything is doing something you don't expect

#

hailstone is showing as undefined in the bottom right? might be why the text area is blank

#

Also your while loop never ends since you never update the num value in your loop so it's never = 1

#

And your steps is always 1 since index = 0 then at the end it's just index + 1
I assume you want to add index++ to your while loop

#

and if you do "index + 1" in a string you're just going to get literally a 1 on the end

e,g if index is 3 your ouput will be "Steps: 31"

nimble glen
# vivid swan I think this is like javascript but not
var hailstone = 0;
var num = 0;
var index = 0;

function testing1() {
  num = 3;
  console.log(num);
  while(num != 1) {
        index++;
    if(num & 2 != 0) {
      hailstone = (num * 3) + 1;
      console.log(hailstone);
      num = hailstone;
    } else {
      hailstone = (num / 2);
      console.log(hailstone)
      num = hailstone;
    }
  }
  updateScreen();
}
function updateScreen() {
  textSteps = "steps: " + index;
  textOutput = "output: " + hailstone;
  console.log(textOutput);
  console.log(textSteps);
}
testing1();

Did some testing (but I actually wrote it out) and I think this is what you want pretty much

num = 3 results in
"output: 1"
"steps: 7"

#

console.log stuff is just for seeing what happens you don't need it at the end but u can adjust it to work how u want it

vivid swan
#

yeah my while loop made my list keep appending the same value 😭

tepid quarryBOT