Chris Bilson
Chris Bilson

Reputation: 1904

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.

Upvotes: 0

Views: 5889

Answers (3)

obchardon
obchardon

Reputation: 10792

The solutions above suggest to use N choose K and then unique but we can easily and directly compute the divisors from the prime factors:

function x = divisors(n)
    f = factor(n);    
    u = unique(f);
    c = histc(f,u);
    
    x = [1,u(1).^(1:c(1))].';
    for ii = 2:length(u)
        x = (x.*[1,u(ii).^(1:c(ii))])(:);
    end
end

You can just add some if/else to manage the exotic case (n=0 or n<0).

Upvotes: 0

Michael Naghavipour
Michael Naghavipour

Reputation: 11

I thing this is the one you are looking for. Hope it could be useful.

MATLAB / Octave

function fact(n);
f = factor(n);  % prime decomposition    
K = dec2bin(0:2^length(f)-1)-'0';   % generate all possible permutations    
F = ones(1,2^length(f));        
for k = 1:size(K)      
   F(k) = prod(f(~K(k,:)));         % and compute products    
end;     
F = unique(F);                      % eliminate duplicates    
printf('There are %i factors for %i.\n',length(F),n);    
disp(F);  
end;' 

And the following is the Output:

>> fact(12)
There are 6 factors for 12.
    1    2    3    4    6   12
>> fact(28)
There are 6 factors for 28.
    1    2    4    7   14   28
>> fact(64)
There are 7 factors for 64.
    1    2    4    8   16   32   64
>>fact(53)
There are 2 factors for 53.
    1   53

Upvotes: 1

mtrw
mtrw

Reputation: 35098

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

Upvotes: 1

Related Questions