在下面的代码中,有一个我不明白的问题。在这些行中:
gcd = GCD(n, A);
lcm = LCM(n, A);
尽管我没有使用指针,但是在GCD功能之后,数组A [n]元素已经改变了。因此,第二个功能没有正常工作。所以,如果我颠倒了上面两行的顺序,这次GCD功能将无法正常工作。我的错是什么?
/*
Finding the greatest common divisor and the least common multiple in an array.
*/
#include <stdio.h>
int GCD(int n, int A[]);
int LCM(int n, int A[]);
int main()
{
int n, gcd, lcm;
printf("Length of the array?: ");
scanf("%d", &n);
int A[n];
for (int i = 0; i < n; i++)
{
printf("Element #%d: ", i+1);
scanf("%d", &A[i]);
}
gcd = GCD(n, A);
lcm = LCM(n, A);
printf("\ngcd: %d\nlcm: %d\n", gcd, lcm);
return 0;
}
int GCD(int n, int A[]) // Greatest common divisor
{
int gcd = 1, j = 1, flag, ones = 0;
while (1)
{
flag = 0;
for (int i = 0; i < n; i++)
{
if (A[i] % j == 0)
{
A[i] /= j;
flag++;
if (A[i] == 1)
ones++;
}
}
if (flag == 0 || j == 1)
j++;
else
gcd *= j;
if (ones == n)
return gcd;
}
}
int LCM(int n, int A[]) // Least common multiple
{
int lcm = 1, j = 2, flag = 0, ones = 0;
for (int i = 0; i < n; i++)
if (A[i] == 1)
flag++;
if (flag != 0)
return 1;
while (1)
{
for (int i = 0; i < n; i++)
{
if (A[i] % j == 0)
{
A[i] /= j;
flag++;
if (A[i] == 1)
ones++;
}
}
if (flag == n)
lcm *= j;
if (flag == 0)
j++;
if (ones == n)
return lcm;
flag = 0;
}
}