2018-11-29 13:07

# C语言求最大公约数问题

2 4
12 6
3 5
0 0

2
6
1

`````` #include<stdio.h>

int gcd(int a,int b)
{
if(a==0&&b!=0)
return b;
else if(a!=0&&b==0)
return a;
else if(a==1||b==1)
return 1;
else
{
int t;
while(b!=0)
{
t=a%b;
a=b;
b=t;
}
return a;
}
}

int main()
{
int a,b;
while(1)
{
scanf("%d %d",&a,&b);
if(a==0&&b==0)
break;
printf("%d\n",gcd(a,b));
}
return 0;
}
``````
• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

• # 如果问题得到解决，请点我回答左上角的采纳和向上的箭头，谢谢

``````#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
int x;
node * next;
} * List;

int gcd(int a,int b)
{
if(a==0&&b!=0)
return b;
else if(a!=0&&b==0)
return a;
else if(a==1||b==1)
return 1;
else
{
int t;
while(b!=0)
{
t=a%b;
a=b;
b=t;
}
return a;
}
}

int main()
{
int a,b;
List list = NULL;
node * p = NULL;
while(1)
{
scanf("%d %d",&a,&b);
if(a==0&&b==0)
break;
if (!list)
{
list = p = (node *)malloc(sizeof(node));
p->x = gcd(a,b);
p->next = NULL;
}
else
{
p->next = (node *)malloc(sizeof(node));
p = p->next;
p->x = gcd(a,b);
p->next = NULL;
}
}
p = list;
while (p)
{
printf("%d\n",p->x);
p = p->next;
}
return 0;
}

``````
点赞 评论