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

2023-09-11 07:02:10 作者:浅笑、那末路繁华

我想写在MATLAB一个功能,可以快速地确定数组是否是互质。在形式上,我们说一个N×1阵列 X 是互质,如果最大的正整数,把所有的N个元素为1(看到这里,了解更详尽的定义)。

I would like to write a function in MATLAB that can quickly determine whether an array is coprime. Formally, we say that an N x 1 array x is coprime if the largest positive integer that divides all N elements is 1 (see here for a more extensive definition).

这是我心目中的职能应输入整数数组 X ,输出如果x互质。一些例子:

The function that I have in mind should input an array of integers x, and output true if x is coprime. Some examples:

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

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

答案在这个目前最好的尝试是:

Answer The current best attempt at this is:

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

任何人都可以提出一个更快的方法?

Can anyone suggest a faster method?

推荐答案

您可以使用的内置的MATLAB函数寻找最大公约数(GCD)为每两个连续的数字数组中,积累的结果在某些变量GCD。如果GCD = 1,则这些数字互质。否则,他们不会互质和GCD是他们的共同因素。

You can use the built in MATLAB function for finding the Greatest Common Divisor (GCD) for every two consecutive numbers in the array and accumulate the result in some variable GCD. If GCD = 1, then the numbers are coprime. Otherwise, they are not coprime and GCD is their common factor.

下面是code:

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