Cod*_*bau 2 c arrays for-loop greatest-common-divisor
我正在尝试用C编写程序.程序应该找到给定数组的GCD(最大公约数).我试图使用最小数量的数组来找到GCD.我想知道我上一次循环的错误.我没有想办法如何检查除法是否给出任何小数点以便停止循环.这是我的代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
int A[10]={112, 160, 180, 240, 288, 32, 480, 96, 60, 72};
int i;
int j;
int minimum = A[0];
int GCD;
int temp;
for (i=1;i<9;i++)
{
if( A[i] < minimum)
{
minimum = A[i];
}
}
for (i=1; i < minimum/2; i++)
{
for (j = 0; j < 9;j++)
{
GCD = 2*i;
temp = ((A[j])/(GCD));
int check = temp%1;
if (check == 0)
break;
}
}
printf("The Greates Common Denominator is: %d", GCD);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
#include <stdio.h>
unsigned gcd(unsigned x, unsigned y){
unsigned wk;
if(x<y){ wk=x;x=y;y=wk; }
while(y){
wk = x%y;
x=y;
y=wk;
}
return x;
}
int gcd_a(int n, int a[n]){
if(n==1) return a[0];
if(n==2) return gcd(a[0], a[1]);
int h = n / 2;
return gcd(gcd_a(h, &a[0]), gcd_a(n - h, &a[h]));
}
int main(void){
int A[10]={112, 160, 180, 240, 288, 32, 480, 96, 60, 72};
int size_A = sizeof(A)/sizeof(*A);
int gcd = gcd_a(size_A, A);
printf("%d\n", gcd);
return 0;
}
Run Code Online (Sandbox Code Playgroud)