辗转相除法

xiaoxiao2021-02-27  670

//zhan zhuan xiang chu fa 

#include <stdio.h>

main() {     int x,y,a,b,t;     scanf ("MM\n",&x,&y);     if (x > y)     {          t = x;                                                                                                                                //将两数进行比较大小,以便得知辗转相除的顺序。          x = y;          y = t;     }     a = x;     b = y;

    while(b != 0)     //do not used to the "for",because we do not know the number      原来总是习惯性地if语句来进行判断,忽视了while语句的优势。以后应该试试多用while

    {

          t = a % b;           a = b;                                                                                                                            //辗转相除的核心,看着挺简单,其实自己想也不容易。           b = t;     }     printf ("the gdc is:%d\n",a);     printf ("the lcm is:%d\n",x*y/a);

}

总计:认真学习优秀的算法是很有必要的,学习过程中也要将自己的算法和经典的以及别人的进行比较,从中获得更多的算法技巧。

转载请注明原文地址: https://www.6miu.com/read-205.html

最新回复(0)