Skip to content

Latest commit

 

History

History
26 lines (18 loc) · 1.11 KB

98e3.md

File metadata and controls

26 lines (18 loc) · 1.11 KB

Back to questions

98e3: ... 1 4 2 1 4 2 1 ...

Write a Java method int next(int x) that takes a positive integer argument x and returns:

  • x / 2 if x is even
  • 3 * x + 1 if x is odd

Write a program that takes a positive integer command-line argument as an initial value and displays this value, then stores the value in a variable and repeatedly applies next to the variable, displaying each value that is computed. The program should terminate when the value 1 is computed. For instance, given the input 37, your program should print:

37 112 56 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

It is unknown whether this program is guaranteed to terminate for any integer input: the Collatz conjecture posits that it does.

Remember that the main method of your program has an argument args that is an array of type String. Thus the first command-line argument can be accessed via args[0]. To turn this argument into an integer, you can use the parseInt method of the Integer class. E.g.:

int integerVersionOfFirstArgument = Integer.parseInt(args[0]);