Is there a function to find the paired factors of an integer?

26 ビュー (過去 30 日間)
Matt J
Matt J 2022 年 12 月 4 日
コメント済み: John D'Errico 2022 年 12 月 4 日
Is there a function in Matlab to find the pairs of factors that multiply together to give a specified integer, e.g,
F=somefunc(16)
F =
1 16
2 8
4 4

採用された回答

John D'Errico
John D'Errico 2022 年 12 月 4 日
編集済み: John D'Errico 2022 年 12 月 4 日
allfactorpairs = @(n) [divisors(n)',n./divisors(n)'];
allfactorpairs(16)
ans = 5×2
1 16 2 8 4 4 8 2 16 1
If you want only those pairs where the first element is the smaller of the two, then you might write a little function, like this:
allfactorpairs2(16)
ans = 3×2
1 16 2 8 4 4
allfactorpairs2(210)
ans = 8×2
1 210 2 105 3 70 5 42 6 35 7 30 10 21 14 15
allfactorpairs2(137)
ans = 1×2
1 137
Finally, see that this code runs on both doubles as well as syms, and is efficient as long as the number is esily factored, so the limit is really in terms of how well factor works for huge numbers. That of course can be terribly difficult.
allfactorpairs2(sym(factorial(10)))
ans = 
Your choice. Note that divisors is a function from the symbolic toolbox. So if someone finds it is too slow, or you lack that toolbox, it is easily replaced. And while I expect that @Matt J has the symbolic TB, I'll write it the replacement below to operate efficiently on doubles as well as syms.
function D = principaldivisors(N)
% Compute the principal divisors of the scalar variable N, so only those divisors < N.
% Note if N is prime, then this function returns ONLY 1, as the only factor less than N.
F = factor(N);
D = 1;
if numel(F) > 1
% N is composite, so it has more than one divisor less than N
% if N were prime, then 1 and N are the only factors.
for Fi = F
D = unique([D,D*Fi]);
end
D(D == N) = [];
end
end
function pairs = allfactorpairs2(N)
D = principaldivisors(N)';
D(D > sqrt(N)) = [];
pairs = [D,N./D];
end
  2 件のコメント
Matt J
Matt J 2022 年 12 月 4 日
Great! I am surprised, though, that the Symbolic Toolbox is required.
John D'Errico
John D'Errico 2022 年 12 月 4 日
Arguably there should be a utiltiy in MATLAB itself to do this, or even just to find a list of all proper divisors of an integer. But there are relatively few utilities in MATLAB for working with integers, not much more than primes, factor, gcd, lcm, and a few others.
Should there be an expansion of those tools? Perhaps.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by