Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

matlab - Factorization of an integer

While answering another, I stumbled over the question how I actually could find all factors of an integer number without the Symbolic Math Toolbox.

For example:

factor(60)

returns:

 2     2     3     5

unique(factor(60))

would therefore return all prime-factors, "1" missing.

 2     3     5

And I'm looking for a function which would return all factors (1 and the number itself are not important, but they would be nice)

Intended output for x = 60:

 1     2     3     4     5     6    10    12    15    20    30    60     

I came up with that rather bulky solution, apart from that it probably could be vectorized, isn't there any elegant solution?

x = 60;

P = perms(factor(x));
[n,m] = size(P);
Q = zeros(n,m);
for ii = 1:n
    for jj = 1:m
        Q(ii,jj) = prod(P(ii,1:jj));
    end
end

factors = unique(Q(:))'

Also I think, this solution will fail for certain big numbers, because perms requires a vector length < 11.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can find all factors of a number n by dividing it by a vector containing the integers 1 through n, then finding where the remainder after division by 1 is exactly zero (i.e., the integer results):

>> n = 60;
>> find(rem(n./(1:n), 1) == 0)

ans =

     1     2     3     4     5     6    10    12    15    20    30    60

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...