Write a Java method int next(int x)
that takes a positive integer argument x
and returns:
x / 2
ifx
is even3 * x + 1
ifx
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]);