
Basic Data Operation

This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:


Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses


Task

Compute the   factors   of a positive integer.

These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.

(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases).

Note that every prime number has two factors:   1   and itself.



Related tasks

   count in factors
   prime decomposition
   Sieve of Eratosthenes
   primality by trial division
   factors of a Mersenne number
   trial factoring of a Mersenne number
   partition an integer X into N primes
   sequence of primes by Trial Division
   sequence: smallest number greater than previous term with exactly n divisors


 
#lang racket
 
;; a naive version
(define (naive-factors n)
  (for/list ([i (in-range 1 (add1 n))] #:when (zero? (modulo n i))) i))
(naive-factors 120) ; -> '(1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120)
 
;; much better: use `factorize' to get prime factors and construct the
;; list of results from that
(require math)
(define (factors n)
  (sort (for/fold ([l '(1)]) ([p (factorize n)])
          (append (for*/list ([e (in-range 1 (add1 (cadr p)))] [x l])
                    (* x (expt (car p) e)))
                  l))
        <))
(naive-factors 120) ; -> same
 
;; to see how fast it is:
(define huge 1200034005600070000008900000000000000000)
(time (length (factors  huge)))
;; I get 42ms for getting a list of 7776 numbers
 
;; but actually the math library comes with a `divisors' function that
;; does the same, except even faster
(divisors 120) ; -> same
 
(time (length (divisors huge)))
;; And this one clocks at 17ms
 