永发信息网

C语言题目 不太懂

答案:2  悬赏:50  手机版
解决时间 2021-06-07 17:49
  • 提问者网友:蓝琪梦莎
  • 2021-06-06 17:57
题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
1.程序分析:利用辗除法。

2.程序源代码:
#include "stdio.h"
#include "conio.h"
main()
{
int a,b,num1,num2,temp;
printf("please input two numbers:\n");
scanf("%d,%d",&num1,&num2);
if(num1<num2)
{
temp=num1;
num1=num2;
num2=temp;
}
a=num1;b=num2;
while(b!=0)
{
temp=a%b;
a=b;
b=temp;
}
printf("gongyueshu:%d\n",a);
printf("gongbeishu:%d\n",num1*num2/a);
getch();
}

不太懂 这种算法的意思 帮忙注释 解析一下

最佳答案
  • 五星知识达人网友:拾荒鲤
  • 2021-06-06 18:08
#include "stdio.h"
#include "conio.h"
main()
{
int a,b,num1,num2,temp;
printf("please input two numbers:\n");
scanf("%d,%d",&num1,&num2);
if(num1<num2)
{ // 一开始把较大数交换到num1里可以免去一次下面的while循环的执行
temp=num1;
num1=num2;
num2=temp;
}
a=num1;b=num2;
while(b!=0) // 计算 a%b,如果为0,那么b就是最大公约数
{
temp=a%b; // temp = a%b
a=b; // 辗转
b=temp; // b = temp,实际上a%b如果!=0,a和b的最大公约g1数可以转为求b和a%b的最大公约数g2,因为根据数学推导g1是等于g2的,所以这样循环往复下去总有某个时刻a%b=0
}
printf("gongyueshu:%d\n",a); // 最后一次while,a保存为了b,也就是最大公约数
printf("gongbeishu:%d\n",num1*num2/a); // 这个不用解释。。。
getch();
}

关于辗转相除法的包含的数学原理,你可以去百度搜欧几里得算法,地址:
http://baike.baidu.com/view/795549.htm?fr=ala0
全部回答
  • 1楼网友:由着我着迷
  • 2021-06-06 19:39

楼上解释很名了.

答案非楼主莫数了

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯