Newsgroups: comp.lang.apl
Path: watmath!watserv2.uwaterloo.ca!mach1!torn!cs.utexas.edu!zaphod.mps.ohio-state.edu!usc!sol.ctr.columbia.edu!The-Star.honeywell.com!umn.edu!csus.edu!sfsuvax1.sfsu.edu!emclean
From: emclean@sfsuvax1.sfsu.edu (Emmett McLean)
Subject: Factoring numbers
Message-ID: <1993Feb28.015325.18464@csus.edu>
Sender: news@csus.edu
Organization: San Francisco State University
Date: Sun, 28 Feb 1993 01:53:25 GMT
Lines: 80

   NB.  One thing I like about J is the versatility of the language.
   NB.  Here's something I translated this from Touretzy's Common Lisp.
   
   NB.   (defun factors (n)
   NB.    (factors-help n 2))
   NB.   
   NB.   (defun factors-help (n p)
   NB.    (cond ((equal n 1) nil)
   NB.    ((zerop (rem n p))
   NB.     (cons p (factors-help (/ n p) p)))
   NB.    (t (factors-help n (+ p 1)))))
   NB.   
   
   n =. {.
   p =. {:
   cond =. @.
   cons =. ,
   rem =. |~
   zerop =. 0&=
   right =. ]
   incr =. >:
   
   factors =. factors_help@(right cons 2:)  
   
   factors_help  =. fh_cc1`(''"_) cond (1: = n)
   fh_cc1  =. fh_cc2`(p cons factors_help@(( n % p) cons p)) cond (zerop@(n rem p))
   fh_cc2 =.  factors_help@(n cons incr@p)
   factors =. factors_help@(right cons 2:)  
   factors"0  (60 90 )
2 2 3 5
2 3 3 5
   
   NB. And this function for factor trees which explains the
   NB. factorization.
   NB. 
   NB.         60
   NB.        / \
   NB.       2  30 
   NB.         / \
   NB.         2 15
   NB.           / \
   NB.          3  5
   NB.  
   NB.     (defun factor-tree(n)
   NB.       (fact-tree-help n 2))
   NB.     
   NB.     (defun fact-tree-help (n p)
   NB.       (cond ((equal n p) n)
   NB.             ((zerop (rem n p))
   NB.             (list n p (fact-tree-help (/ n p) p)))
   NB.             (t (fact-tree-help n (+ p 1)))))
   
   box =. <
   link =. ;
   
   factor_tree =. factor_tree_help@(right cons 2:) 
   
   factor_tree_help =.ft_cc1`(box@n) cond (n = p)
   ft_cc1 =. ft_cc2`((n link p) cons box@(factor_tree@((n % p) cons p))) cond (zerop@(n rem p))
   ft_cc2 =. factor_tree_help@(n cons incr@p)
   factor_tree"0 ( 60 90 )
+--+-+-----------------+
|60|2|+--+-+----------+|
|  | ||30|2|+--+-+---+||
|  | ||  | ||15|3|+-+|||
|  | ||  | ||  | ||5||||
|  | ||  | ||  | |+-+|||
|  | ||  | |+--+-+---+||
|  | |+--+-+----------+|
+--+-+-----------------+
|90|2|+--+-+----------+|
|  | ||45|3|+--+-+---+||
|  | ||  | ||15|3|+-+|||
|  | ||  | ||  | ||5||||
|  | ||  | ||  | |+-+|||
|  | ||  | |+--+-+---+||
|  | |+--+-+----------+|
+--+-+-----------------+

   
