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 t开发者_Python百科he factor
function, but this only gives the prime factorization. I'd like all the integer divisors.
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
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
Just use "divisors":
divisors(sym(120))
ans = (sym) [1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120] (1×16 matrix)
精彩评论