algorithm - 如何使用 MATLAB 快速检查数组是否互质

标签 algorithm matlab primes discrete-mathematics prime-factoring

我想在 MATLAB 中编写一个函数,可以快速判断一个数组是否互质。形式上,我们说一个 N x 1 数组 x 是互质的,如果整除所有 N 个元素的最大正整数是 1(请参阅此处了解更广泛的 definition)。

我想到的函数应该输入一个整数数组 x,如果 x 是互质的,则输出 true。一些例子:

%example
x = [6,10,15];
iscoprime(x)
> true

%counter-example
x = 2*[1,2,3];
iscoprime(x)
> false

回答 目前最好的尝试是:

function value = iscoprime(x)

%remove 0 and take absolute value
x = abs(x(x==0));
nx = length(x);

%return true if all original entries = 0
if nx == 0, value = true;

%return false if x only contains 1 value and it is not 1
elseif nx == 1 & x~=1, value = false;

%return true if x contains a 1 (easy way to tell if x is coprime)
elseif any(x==1), value = true;

%check if x is coprime (based on Yasen's answer)
else

    v = x(1);
    for i = 2:nx
        v = gcd(v,x(i));
        if (v == 1), 
            value = true;
            break
        end
    end
    value = false;

end
end

谁能推荐一个更快的方法?

最佳答案

您可以使用 the built in MATLAB function用于为数组中的每两个连续数字找到最大公约数 (GCD),并将结果累加到某个变量 GCD 中。如果 GCD = 1,则数字互质。否则,它们不是互质的,并且 GCD 是它们的公因数。

代码如下:

function GCD = iscoprime(x) % assuming x is an array, 
    GCD = x(1);             % returning greatest common divisor for the array
    for i=1:size(x, 2)
        GCD = gcd(GCD, x(i));
    end
end

关于algorithm - 如何使用 MATLAB 快速检查数组是否互质,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20206152/

相关文章:

matlab - 将零填充到二进制数中特定位置的命令?

java - Miller-Rabin 代码对于某些数字运行时间较长。漏洞?

python - 二进制序列 x 位长的所有排列

java - 执行时间和大 O

python - 对 2^30 个 32 位整数进行排序。最佳解决方案

arrays - 处理 Excel 的 VBA 宏中的数组

c++ - openCV 与 matlab 矩阵串联

python - 使用常数空间迭代所有互质对?

algorithm - 在 F# 中查找质数非常慢

algorithm - 在排序数组中查找绑定(bind)给定值的两个连续值的优雅方法?