辗转相除法

#include<stdio.h>

int f(int a,int b)
{
    int c;
    int temp=0;
    if (a<b)
    {
        temp=a;
        a=b;
        b=temp;
    }
    while(a%b!=0)
    {
        c=b;
        b=a%b;
        a=c;
        if (a<b)
        {
            temp=a;
            a=b;
            b=temp;
        }
        printf("%d %d\n",a,b);
    }
    return b;
}

int main()
{
    int a,b;
    scanf("%d",&a);
    scanf("%d",&b);
    b=f(a,b);
    printf("%d",b);
}
/*

思路:


输入a,b两个数字


传入函数中


把a和b按照大小排序


进入辗转相除的循环中,


当a%b不等于0时,就一直让a%b,把a%b的值存入b中,原来b的值存入a中。


返回最后的b(b就是最大公约数)

*/

 1 a=int(input("输入数字1:"))
 2 b=int(input("输入数字2:"))
 3 while (b >0 and a != 0):
 4         if a >b:
 5             a= a%b
 6         elif a<b:
 7             b = b%a
 8         elif a == b:
 9             break
10 if a>=b:
11     print("f最大公约数是",a)
12 elif a<=b:
13     print("f最大公约数是",b)

 

 

 可以参考一下图片

posted @ 2021-11-03 13:42  20212301guo  阅读(306)  评论(0)    收藏  举报