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

hello world.

文章分类

全部博文(308)

分类: C/C++

2010-08-06 15:27:10

    写两个函数,分别求两个整数的最大公约数和最小公倍数。用主函数调用这两个函数,并输出结果,两个整数有键盘输入。
   我们知道,求最大公约数的方法是:用迭代法,让两个数求余。然后将求余结果作为除数,原来的除数作为被除数。知道除数为零,则被除数即为最大公约数;而最小值公倍数的求法是:输入的两个数相乘然后除于最大公约数即可。根据上面的原理,编写如下代码:
 

#include <stdio.h>

int maxgongyueshu(int,int);
int mingongbeishu(int,int);
int main(int argc, int *argv[])
{
    int a,b;
    printf("please input 2 numbers:");
    scanf("%d,%d",&a,&b);
    printf("the maxgongyueshu : %d ,the mingongbeishu : %d",
                maxgongyueshu(a,b),mingongbeishu(a,b));
    system("pause");
    return 0;
}

int maxgongyueshu(int m,int n)
{
    int a,b,temp;
    if (m >= n)
    {
          a = m;
          b = n;
    }
    else
    {
        a = n;
        b = m;
    }
    
    do
    {
        temp = a % b;
        a = b;
        b = temp;
    }while (b);
    return a;
}

int mingongbeishu(int m,int n)
{
    return m * n / maxgongyueshu(m,n);
}


阅读(6536) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~