Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2508842
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2011-03-30 08:55:02

    我们上小学的时候,我们都学习过求两个数的最大公约数,最小公倍数。求最大公约数的思想是,找出两个书中的最小数,然后用两个数对其求余,如果两个数求余的结果为零,则此时最大公约数。否则将其最小数减一,进行循环判断。求最小公倍数时,现找出两个数中的最大数,然后进行加一操作,求余。当两个数求余都为0即可求出最小公倍数。代码如下:
  1. #include <stdio.h>

  2. int gcd(int a, int b)
  3. {
  4.   int min;
  5.   if(a <= 0 || b <= 0) return -1;
  6.   if(a > b) min = b;
  7.   else min = a;

  8.   while(min)
  9.   {
  10.     if (a % min == 0 && b % min == 0)
  11.       return min;
  12.     min--;
  13.   }
  14.   return -1;
  15. }

  16. int lcm(int a, int b)
  17. {
  18.   int max;
  19.   if(a <= 0 || b <= 0)
  20.     return -1;

  21.   if(a > b)
  22.     max = a;
  23.   else
  24.     max = b;
  25.   
  26.   while(max)
  27.   {
  28.     if(max % a == 0 && max % b == 0)
  29.       return max;
  30.     
  31.     max++;
  32.   }

  33.   return -1;
  34. }

  35. int main(int argc, char *argv[])
  36. {
  37.   int a,b;
  38.   printf("please input two digit for getting GCD and LCM\n");
  39.   scanf("%d %d",&a,&b);
  40.   printf("the GCD of %d and %d is %d\n",a,b,gcd(a,b));
  41.   printf("the LCM of %d and %d is %d\n",a,b,lcm(a,b));
  42.   return 0;
  43. }
peng@ubuntu:~$ ./a.out 
please input two digit for getting GCD and LCM
4 10
the GCD of 4 and 10 is 2
the LCM of 4 and 10 is 20
阅读(1826) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~