Calculate the Greatest Commom Divisor (GCD) and Lowest Common Multiple (LCP) of Two Integers

1. 用更相减损法求最大公约数,所谓更相减损法,即“以少减多,更相减损,求其等也,以等数约之,等数约之,即除也,其所以相减者皆等数之重叠,故以等数约之”。

// Calculate the Greatest Common Divisor (GCD) of two numbers

int gcd(int a, int b)
{
	while (b != a)
	{
		if (a > b)
			a = a - b;
		if (a < b)
			b = b - a;
	}
	return a;//or return b since a and b are equal at this moment.
}

#include<stdio.h>
int main()
{
	int x, y, z;
	printf("Please input two integers:\n");
	scanf("%d %d",&x,&y);
	z = gcd(x, y);
	printf("The GCD of these two numbers are %d\n",z);
        return 0;
}

or:

// Calculate the Greatest Common Divisor (GCD) of two numbers

int gcd(int a, int b)
{	
        if(a < b)
           return gcd(b, a);
        if(b == 0)
           return a;
        else 
           return gcd(a-b, b);
}

#include<stdio.h>
int main()
{
	int x, y, z;
	printf("Please input two integers:\n");
	scanf("%d %d",&x,&y);
	z = gcd(x, y);
	printf("The GCD of these two numbers are %d\n",z);
        return 0;
}

Input:

Please input two integers:
6 9
Output:

The GCD of these two numbers are 3

2. 用辗转相除法求最大公约数,所谓辗转相除法,即 “两个整数的最大公约数等于其中较小的数和两数的相除余数的最大公约数”.

int GCD(int m, int n)
{
	int t,r; 
	if (m < n)
	{
		t = m;
		m = n;
		n = t;
	}
	r = m % n;
	if (r == 0)
		return n;
		
	else 
		return GCD(r,n); 


}


#include<stdio.h>
int main()
{
	int x, y, res;
	printf("Please input two numbers:\n");
	scanf("%d %d", &x, &y);
	res = GCD(x, y);
	printf("The GCD of %d and %d is %d\n", x, y, res);
        return 0;
}

or:

int GCD(int m, int n)
{       
        int t; 
	if (m < n)
	{
		t = m;
		m = n;
		n = t;
	}
	return (!n)?m:GCD(n,m%n);
}


#include<stdio.h>
int main()
{
	int x, y, res;
	printf("Please input two numbers:\n");
	scanf("%d %d", &x, &y);
	res = GCD(x, y);
	printf("The GCD of %d and %d is %d\n", x, y, res);
        return 0;
}

Input:

Please input two integers:
6 9
Output:

The GCD of these two numbers are 3



3. 两个数的 最小公倍数等于两个数的乘积除以最大公约数。

// Calculate the Lowest Common Multiple (LCP) of two intergers
int gcd(int a, int b)
{
	while (b != a)
	{
		if (a > b)
			a = a - b;
		if (a < b)
			b = b - a;
	}
	return a;
}

#include<stdio.h>
int main()
{
	int x, y, z;
	printf("Please input two integers:\n");
	scanf("%d %d",&x,&y);
	z = (x * y) / gcd(x, y);
        printf("The LCP of these two intergers is %d\n",z);
        return 0;
}
        

Input:

Please input two integers:
6 9
Output:

The LCP of these two numbers are 18




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值