Advertisement
Guest User

grepmonster

a guest
Dec 12th, 2008
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. /*
  2.  * ----------------------------------------------------------------------------
  3.  * "THE BEER-WARE LICENSE" (Revision 42):
  4.  * grepmonster.wordpress.com wrote this file. As long as you retain this notice you
  5.  * can do whatever you want with this stuff. If we meet some day, and you think
  6.  * this stuff is worth it, you can buy me a beer in return. Eddy
  7.  * ----------------------------------------------------------------------------
  8.  */
  9.  
  10. public class Halt
  11. {
  12.   public static void main(String [] args)
  13.   {
  14.     //If we are given arguments, convert them to an int and pass to f
  15.     if (args.length > 0)
  16.     {
  17.       long input;
  18.      
  19.       for (String string: args)
  20.       {
  21.         try
  22.         {
  23.           input = Long.parseLong(string);
  24.          
  25.           if (input < 0)
  26.           {
  27.             throw new NumberFormatException();
  28.           }
  29.          
  30.           f(input);
  31.           System.out.println();
  32.           System.out.println("--------------------------------------------------------------------------------");
  33.         }
  34.         catch (NumberFormatException e)
  35.         {
  36.           System.err.println("Argument must be a natural number");
  37.           System.exit(1);
  38.         }
  39.       }
  40.     }
  41.     else
  42.     {
  43.         //Try all inputs starting from 0
  44.       long input = 0;
  45.      
  46.       while (true)
  47.       {
  48.         f(input);
  49.         System.out.println();
  50.         System.out.println("--------------------------------------------------------------------------------");
  51.         input++;
  52.       }
  53.     }
  54.   } // main
  55.  
  56.   private static void f(long x)
  57.   {
  58.     System.out.print(x);
  59.    
  60.     while (x > 1)
  61.     {
  62.       //if x is even x := x / 2
  63.       if (x % 2 == 0)
  64.       {
  65.         x /= 2;
  66.       }
  67.       //otherwise x := 3x + 1
  68.       else
  69.       {
  70.         x = (3 * x) + 1;
  71.       }
  72.      
  73.       System.out.print(", " + x);
  74.     }
  75.    
  76.     System.out.print(", halt.");
  77.   } //f
  78. } //Halt
  79.  
  80.  
  81.  
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement