【问题标题】:How can I compute all factors of a number in octave (not just prime factors)?如何计算八度音阶中数字的所有因子(不仅仅是素因子)?
【发布时间】:2011-10-15 18:33:35
【问题描述】:

我是 Octave 新手,想计算一个数字的所有整数除数,例如,对于数字 120,我想得到 1、2、3、4、5、6、8、10 、12、15、20、24、30、40、60 和 120。

我知道 octave 有 factor 函数,但这只会给出素数分解。我想要所有的整数除数。

【问题讨论】:

  • Optimizing Matlab Code 的可能副本,它提供了获取单个数字的所有因子以及范围内每个数字的所有因子的方法。

标签: octave


【解决方案1】:

我认为没有内置函数,所以你需要编写一个。由于每个因子都是主要因子子集的乘积,因此您可以使用一些内置函数来构建所需的结果。

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

【讨论】:

  • 这看起来像是对stackoverflow.com/questions/7640010/optimizing-matlab-code/…的一个非常轻微的修改,如果是你应该给@b3当之无愧的功劳。
  • @Ben - 你说得对,它几乎是一样的。不过,我之前没有看到其他问题。我很高兴看到我与 b3 在如何简单有效地执行此计算方面达成了一致。
【解决方案2】:

我认为这就是您要找的那个。 希望对你有用。

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;' 

以下是输出:

>> 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

【讨论】:

    【解决方案3】:

    只需使用“除数”:

    divisors(sym(120))
    
    ans = (sym) [1  2  3  4  5  6  8  10  12  15  20  24  30  40  60  120]  (1×16 matrix)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 2015-06-05
      • 2011-03-27
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多