C趣味编程百例(13)最大公约数和最小公倍数 |
|
www.nanhushi.com 佚名 不详 |
42.最大公约数和最小公倍数 求任意两个正整数的最大公约数和(GCD)和最小公倍数(LCM) *问题分析与算法设计 手工方式求两个正整数的蝚大公约数的方法是用辗转相除法,在程序中可以模拟这种方式。 *程序与程序注释 #include<stdio.h> void main() { int a,b,num1,num2,temp; printf("Input a & b:"); 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("The GCD of %d and %d is: %d\n",num1,num2,a); /*输出最大公约数*/ printf("The LCM of them is: %d\n",num1*num2/a); /*输出最小公倍数*/ } *运行结果 1.Input a & b: 20 55 The GCD of 20 and 55 is: 5 The LCM of them is: 220
2.Input a & b: 17 71 The GCD of 17 and 71 is: 1 The LCM of them is: 1207
3.Input a & b: 24 88 The GCD of 24 and 88 is: 8 The LCM of them is: 264
4.Input a & b: 35 85 The GCD of 35 and 85 is: 5 The LCM of them is: 595
*思考题 求一个最小的正整数,这个正整数被任意n(2<=n<=10)除都是除不尽的,而且余数总是(n-1)。例如:被9除时的余数为8。要求设计一个算法,不允许枚举与除2、除3、....、除9、除10有关的命令,求出这个正整数。
|
|
|
文章录入:杜斌 责任编辑:杜斌 |
|
上一篇文章: C趣味编程百例(12)马克思手稿中的数学题 下一篇文章: C趣味编程百例(13)分数比较 |
【字体:小 大】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口】 |
|
|