allFactors2.frink

Download or view allFactors2.frink in plain text format


// This function finds all divisors of a number, including 1 and the number
// itself.  This version uses the "multifor" construct to simplify the logic.

allFactors[n, include1=true, includeN=true, sort=true, onlyToSqrt=false] :=
{
   factors = factor[n]
   size = length[factors]

   if onlyToSqrt = false
      upperLimit = n
   else
      upperLimit = floor[sqrt[n]]

   /* We can precalculate the size of the results.  Each base in the factor
      list multiplies the total factors by exp+1 */

   resultSize = 1
   for [base,exp] = factors
      resultSize = resultSize * (exp+1)

   results = new array[resultSize]

   loops = new array[size]
   for [base,count] = factors
      loops.push[new range[0,count]]

   multifor c = loops
   {
      product = 1
      for i = 0 to length[c]-1
         product = product * (factors@i@0)^(c@i)

      if (product > upperLimit)
         next

      if ((product == 1 and include1 == false) or (product == n and includeN == false))
      {
         // Do nothing
      } else
         results.push[product]
   }

   if sort
      sort[results]   // Sorts in place
   return results
}

"allFactors included successfully."


Download or view allFactors2.frink in plain text format


This is a program written in the programming language Frink.
For more information, view the Frink Documentation or see More Sample Frink Programs.

Alan Eliasen was born 20143 days, 10 hours, 59 minutes ago.