求两个数的最大公约数。
最大公约数:有两个数i,j(i和j都能整除的最大整除),先比较出较小的那个数(设为j,若i大,则利用比较,把i的值赋给j),定义一个临时变量n,n的值从j到1递减,在此递减过程一旦有i和j都能整除n,则n为i和j的最大公约数,跳出for循环。
{题外话:
最小公倍数:两个数i和j(能整除i和j的最小整数),先比较出i和j中比较大的数,定义变量n,n的值从较大的数开始逐个递增到i*j的值结束(i与j的积一定能整除i和j,但不一定是最小的),在此递增过程中,若有n能整除i和j,则n为他们两个的最小公倍数,跳出for循环。
}
#include <stdio.h>
#include <windows.h>
int main(){
int i, j;
int div;
int n;
int temp;
printf("Please enter two num:");
scanf_s("%d%d",&i,&j);
if (i<j){
temp = i;
i = j;
j = temp;
}
for (n = j; n >= 1;n--){
if (i%n==0&&j%n==0){
div = n;
break;
}
}
printf("the max div of %d %d is %d",i,j,div);
system("pause");
return 0;
}
老师代码:(辗转相减)
#include <stdio.h>
#include <windows.h>
#define _CRT_SECURE_NO_WARNINGS 1
int main(){
int x, y;
printf("Please enter two number :");
scanf_s("%d%d",&x,&y);
while (1){
if (x>y){
x = x - y;
}
else if (y>x){
y = y - x;
}
else{
break;
}
}
printf("%d", x);
system("pause");
return 0;
}