如果数组中有超过2个值,如何查找GCD?
我正在考虑找到最小的值,并尝试将数组中的每个元素除以它,如果mod不为0,则从该值中取出1并重新开始。
但是我只得到0所以这是错误的方式,任何想法?
program GreatestCommonDivisor;
type mas = array[1..100] of integer;
var n : integer;
M : mas;
Rf : text;
procedure Skaityti;
var i : integer;
Df : text;
begin
Assign(Df,'duom1.txt');
Reset(Df);
Readln(Df,n);
for i := 1 to n do
Read(Df,M[i]);
Close(Df);
end;
function GCD(M : array of integer): integer;
var i,min : integer;
begin
min := M[1];
for i := 1 to n do
begin
if min > M[i] then
min := M[i];
end;
i := 1;
repeat
if M[i] mod min = 0 then
GCD := min
else
begin
min := min - 1 ;
i := 0;
continue;
end;
i := i + 1;
until i = n;
end;
var min,i : integer;
begin
Skaityti;
Assign(Rf,'rez.txt');
for i := 1 to n do
Writeln(Rf,GCD(M),' ',min);
Close(Rf);
end.
答案 0 :(得分:1)
不确定您的输入是什么,但我认为您在推理中存在缺陷:
首先,您尝试找到最小元素作为潜在的gcd。合理的假设,gcd当然不能大于此。然而,然后你循环通过你的列表,如果假设的gcd没有均匀分配你将它减少一个并继续。这不起作用。
Start = 10, 9, 8; min = 8; gcd is undefined (defaults to 0)
10 mod 8 is not 0, so min = 7
9 mod 7 is not 0, so min = 6
8 mode 6 is not 0, so min = 5
Done, gcd is now 0
Start = 10, 9, 8, 5, min = 5, gcd is undefined (defaults to 0)
10 mod 5 is 0, so gcd = 5
9 mod 5 is not 0, so min = 4
8 mod 4 is 0, so gcd = 4
5 mod 4 is not 0 so min = 3
Done, gcd is now 4
这是一个计算gcd(低效率)的程序
Program ShowGCD(output);
type
arr = array of integer;
var
M: arr;
function GCD(M: arr ): integer;
var i,min : integer;
begin
min := M[0];
for i := 1 to Length(M)-1 do begin
if min > M[i] then
min := M[i];
end;
i := 1;
repeat
if M[i] mod min = 0 then
GCD := min
else
begin
min := min - 1;
i := 0;
continue;
end;
i := i + 1;
until i = Length(M);
end;
begin
M:=arr.Create(15, 45, 25);
writeln('GCD: ', GCD(M));
end.