Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * ----------------------------------------------------------------------------
- * "THE BEER-WARE LICENSE" (Revision 42):
- * grepmonster.wordpress.com wrote this file. As long as you retain this notice you
- * can do whatever you want with this stuff. If we meet some day, and you think
- * this stuff is worth it, you can buy me a beer in return. Eddy
- * ----------------------------------------------------------------------------
- */
- public class Halt
- {
- public static void main(String [] args)
- {
- //If we are given arguments, convert them to an int and pass to f
- if (args.length > 0)
- {
- long input;
- for (String string: args)
- {
- try
- {
- input = Long.parseLong(string);
- if (input < 0)
- {
- throw new NumberFormatException();
- }
- f(input);
- System.out.println();
- System.out.println("--------------------------------------------------------------------------------");
- }
- catch (NumberFormatException e)
- {
- System.err.println("Argument must be a natural number");
- System.exit(1);
- }
- }
- }
- else
- {
- //Try all inputs starting from 0
- long input = 0;
- while (true)
- {
- f(input);
- System.out.println();
- System.out.println("--------------------------------------------------------------------------------");
- input++;
- }
- }
- } // main
- private static void f(long x)
- {
- System.out.print(x);
- while (x > 1)
- {
- //if x is even x := x / 2
- if (x % 2 == 0)
- {
- x /= 2;
- }
- //otherwise x := 3x + 1
- else
- {
- x = (3 * x) + 1;
- }
- System.out.print(", " + x);
- }
- System.out.print(", halt.");
- } //f
- } //Halt
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement