$factors(N) <- return N factors (3 formats)

By vaseline28 on Jun 14, 2008

Returns the Factors of N
Factors: Numbers which multiplied by another number go into the target.
e.g. 12 (1 x 12), (2 x 6), (3 x 4) = 12
1,12,2,6,3,4 are factors of 12

; Usage: $factors(N).P
; 'P' above can be: List (List factors) || group (factors grouped like (F,F)) || num (Number of factors)
; Example I: $factors(2).list <--- Returns 1 2
; Example II: $factors(15).group <--- Returns (1,15) (3,5)
; Example III: $factors(372).num <--- Returns 12

I searched around and couldn't find an in-built function for this (I hope there isn't one now I've made it!)

; Usage: $factors(N).P
; 'P' above can be: List (List factors) || group (factors grouped like (F,F)) || num (Number of factors)
; Example I: $factors(2).list  <--- Returns 1 2
; Example II: $factors(15).group <--- Returns (1,15) (3,5)
; Example III: $factors(372).num <--- Returns 12
alias factors {
  if ($isid) {
    var %x 0 | var %t
    while (%x < $calc($1 / 2)) {
      inc %x
      if ( . !isin $calc($1 / %x %y)) {
        if (($prop == list) || ($prop == num)) $iif(%x isin %t,,set %t %t %x $calc($1 / %x))
        elseif ($prop == group) $iif(%x isin %t,,set %t %t ( $+ %x $+ , $+  $calc($1 / %x) $+ ))
      }
    }
    if ($prop = num) set %t $numtok(%t,32)
    var %y %t | unset %t
    return %y
  }
}

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.