#!/bin/csh
#
# factor.csh - Matt Mahoney, mmahoney@cs.fit.edu, Feb. 8, 2004
#
# factor.csh works like the UNIX factor command. If a number is
# given on the command line, the the program prints it and its prime
# factors in ascending order, e.g.
#
# factor.csh 24
# 24
# 2
# 2
# 2
# 3
#
# If there is no argument, then the numbers are repeatedly read from
# input until 0 is entered, and the factors of each are printed.
# If any number is negative, then the program prints "Ouch!".
# Only numbers within the range of a 32 bit signed integer
# (2147483647) can be factored correctly.
if ($#argv > 1) then
echo "Usage: factor number"
exit
endif
set in = () # line of input
while ( 1 ) # input loop, get n to factor
if ($#argv >= 1) then # use number on command line
set n = $1
echo $n
else # get a list of numbers from input
while ($#in == 0)
set in = ( `echo $<` ) # split input into words on whitespace
end
set n = $in[1]
shift in
endif
# Treat n < 2 as a special case
if ($n < 0) echo "Ouch\!"
if ($n == 0) echo " " 0
if ($n == 1) echo " " 1
# Factor n by testing for divisibility by 2,3,5,7,9,11...sqrt(n)
# and removing factors as they are found
while ($n > 1 && $n % 2 == 0) # print factors of 2
echo " " 2
@ n /= 2
end
set f = 3 # print odd factors up to sqrt(n)
while ($f * $f <= $n)
if ($n % $f == 0) then
echo " " $f
@ n /= $f
else
@ f += 2
endif
end
if ($n > 1) echo " " $n # leftover factors?
echo
# More input?
if ($n == 0 || $#argv >= 1) exit
end