题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
分析:最大公约数是:被这两个数除以,余数是0的数中最大一个;最小公倍数:是被这两个数除,余数为0的数中,最小的一个。两个数的乘积除以最大公约数所得值就是最小公倍数。
方法一:辗除法
#include<stdio.h>
void 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)/*利用辗除法,直到b为0为止*/
{
temp=a%b;
a=b;
b=temp;
}
printf("the largest common divisor is:%d\n",a);
printf("the smallest common multiple is:%d\n",num1*num2/a);
}
方法二:
我希望找到一种让程序简洁的办法,利用条件表达式,见下面的代码:
|
#include <stdio.h> void main() { int m,n,i,z; printf("pls input two number:\n"); scanf("%d%d",&m,&n); z=m>n?m:n; /*z=m>n?n:m;此处无差别*/ for(i=z;i>0;i--) if(m%i==0&&n%i==0) break; /*只取第一个余数为零的除数即为最大公约数*/ printf("largest common divisor is:%d\n",i); printf("smallest common multiple is:%d\n",m*n/i); system("pause"); } |
浙公网安备 33010602011771号