math - Ruby while loop only executes once -


This code is not working. I am trying to code the codeet, but the code is only for input Runs 1 time It prints from 4, 1, 1 and it shows that it only moves for one step. The second block is never executed Can someone tell me what is wrong with this Ruby Code? I do not know how this is not working. Collatz def collatz (number) if number == 1 return 0 end phase = 0 while the number> 1 If the number% 2 == 0 number = number / 2 number keeps the step, step = moves + 1 step and the second number = (number * 3) + 1 puts number phase = step + 1 puts the step end return Step End End Step = Collatz .new.collatz (8) puts the end of the phase

You have a return statement that is executing the executable after the loop first runs.

Try

  Square Collatz def collatz (number) 0 if number == 1 step = 0 while the number> 1 if the number% 2 puts the points == 0 / = 2 puts the step + = 1 and the number = (number * 3) + 1 puts the step + step = end end of the end phase phase end = collatz Returns the .new.collatz (8) step   

which gives 3 and prints

  4 1 2 2 1 3 [Finished 0.4]]   

And if you want to make your code a bit cleaner and more idioms, then you can reflection it as follows:

  class Collatz def collatz (number) 0 if the number = = 1 step = 0 while the number & gt; 1 number = number as well? ? Number / 2: (number * 3) + 1 points, phase + = 1 end end of end phase end = Collatz.new.collatz (8) # 4 # 1 # 2 # 2 # 1 # 3 # = & gt; ; 3    

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -