Have you heard of the "Hailstone Problem"?

   Pick n > 0 and odd, multiply by three,
   add one, cast out all factors of two, 
   cook 'til (d)one.

   http://www.dyalog.com/dfnsdws/n_ratrep.htm 
   (at the bottom)

Here's my initial formulation in J:

           hail       =:  ([: {.@(% 2 ^ 1&q:) 1 + 3 * ] + 1 - 2&|)^:a: 
           hailstone  =:  hail@:(1 + ?)

           require 'plot'
           plot hail 1e6
           
But I'm not particularly satisfied with my solution to "cast out all factors of 
two".  For one thing, it seems a bit redundant; I mention the constant 2 twice 
(once explicitly with  2^  and once implicitly with  1&q:  ).  So I thought 
about the longer but more general:

           castOut    =:  2&$: : (] % [ ^ (q:~ 1 + _1&p:)~)   NB.  x is prime

Can you improve this verb?  Can you generalize it to cast out all (positive 
integer) factors of  N  where  N  isn't neccesarily prime (e.g.  4&castOut )?

-Dan

PS:  A secondary nit to pick:  I don't like the way I pick "n > 0 and odd".  
Picking n even is short and pretty (+2&|)@(1+?)  but picking n odd is longer   
(+1-2&|)@(1+?)  or   (+-.@(2&|))@(1+?)  .  Is there a shorter way?  
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to