查找数组code C语言GCD [英] Finding GCD of Array Code C language
本文介绍了查找数组code C语言GCD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用C编写的程序应该找到一个给定的数组的GCD(最大公约数)的程序。我试图使用数组的最小号来找到GCD。我想知道什么是错我的最后的循环。我还没有想出如何检查师是为了停止循环给予任何小数点的一种方式。这是我的code
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;诠释的main()
{
INT A [10] = {112,160,180,240,288,32,480,96,60,72};
INT I;
诠释J;
INT最小= a [0];
INT GCD;
INT温度; 对于(i = 1; I< 9;我++)
{
如果(A [1] - ;最低)
{
最小= A [I]
}
} 对于(i = 1; I<最小/ 2;我++)
{
为(J = 0; J< 9; J ++)
{
GCD = 2 * I;
TEMP =((A [J])/(GCD));
INT检查=气温%1;
如果(检查== 0)
打破;
}
} 的printf(本的greates共同点是:%D,GCD); 返回0;
}
解决方案
的#include<&stdio.h中GT;无符号GCD(无符号X,无符号Y){
无符号周;
如果(X LT,Y){周= X; X = Y; Y =周; }
而(Y){
WK = X%Y;
X = Y;
Y =周;
}
返回X;
}INT gcd_a(INT N,诠释一个[N]){
如果(N == 1)返回一个[0];
如果(N == 2)返回最大公约数(一个[0],A [1]);
INT H = N / 2;
返回最大公约数(gcd_a(H,放大器;一个并[h-1]),gcd_a(正 - H,放大器;一个并[h]));
}诠释主要(无效){
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);
返回0;
}
I am trying to write a program in C. The program is supposed to find the GCD (greatest common divisor) of a given array. I am trying to use the smallest number of the array to find the GCD. I was wondering whats wrong with my last loop. I havent figured a way on how to check if the division is giving any decimal points in order to stop the loop. This is my code
#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;
}
解决方案
#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[h-1]), 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;
}
这篇关于查找数组code C语言GCD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文