octave

How can I compute all factors of a number in octave (not just prime factors)?


I am a beginning Octave user and would like to compute all the integer divisors of a number, for example, for the number 120, I would like to get 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, and 120.

I know octave has the factor function, but this only gives the prime factorization. I'd like all the integer divisors.


Solution

  • I don't think there's a built-in function for this, so you will need to write one. Since each factor is the product of a subset of the prime factors, you can use a few built-in functions to build up the desired result.

    function rslt = allfactors(N)
    %# Return all the integer divisors of the input N
    %# If N = 0, return 0
    %# If N < 0, return the integer devisors of -N
        if N == 0
            rslt = N;
            return
        end
        if N < 0
            N = -N;
        end
    
        x = factor(N)'; %# get all the prime factors, turn them into a column vector  '
        rslt = []; %# create an empty vector to hold the result
        for k = 2:(length(x)-1)
            rslt = [rslt ; unique(prod(nchoosek(x,k),2))];
            %# nchoosek(x,k) returns each combination of k prime factors
            %# prod(..., 2) calculates the product of each row
            %# unique(...) pulls out the unique members
            %# rslt = [rslt ...] is a convenient shorthand for appending elements to a vector
        end
        rslt = sort([1 ; unique(x) ; rslt ; N]) %# add in the trivial and prime factors, sort the list
    end