求最大公约数有两种方法: 更相减损法和辗转相处法 。最小公倍数在求出最大公约数后 两个数相乘除以最大公约数就是最小公倍数。
更相减损法更相减损法是拿两个数中的较大值减去较小值,然后在减数、被减数、差之间选取两个较小值继续相减,直到减数和被减数相等,得出的数就是最大公约数。
辗转相除法
用较大数除以较小数,再用出现的余数(第一余数)去除除数,再用出现的余数(第二余数)去除第一余数,如此反复,直到最后余数是0为止。如果是求两个数的最大公约数,那么最后的除数就是这两个数的最大公约数。
题目描述
正整数A和正整数B 的最小公倍数是指 能被A和B整除的最小的正整数值,设计一个算法,求输入A和B的最小公倍数。
输入描述:
输入两个正整数A和B。
输出描述:
输出A和B的最小公倍数。
示例1
输入
5 7
输出
35
C++实现
1. 辗转相除法
#include<iostream>
using namespace std;
int maxyue(int a, int b)
{
while (a%b)
{
int temp = a;
a = b;
b = temp%b;
}
return b;
}
int main()
{
int a, b;
while (cin>>a>>b)
{
int yue;
if (a>b)
{
yue=maxyue(a, b);
}
else
{
yue=maxyue(b, a);
}
cout << a * b / yue << endl;
}
return 0;
}
2.更相减损法
#include<iostream>
using namespace std;
int maxyue(int a, int b)
{
int temp = a - b;
while (temp!=b)
{
if (temp>b)
{
a = temp;
b = b;
}
else
{
a = b;
b = temp;
}
temp = a - b;
}
return b;
}
int main()
{
int a, b;
while (cin>>a>>b)
{
int yue;
if (a>b)
{
yue=maxyue(a, b);
}
else
{
yue=maxyue(b, a);
}
cout << a * b / yue << endl;
}
return 0;
}
JAVA实现
1. 辗转相除法
import java.util.Scanner;
public class Main
{
static int maxyue(int a,int b)
{
while (a%b!=0)
{
int temp = a;
a = b;
b = temp%b;
}
return b;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int a=scanner.nextInt();
int b=scanner.nextInt();
int yue;
if (a>b)
{
yue=maxyue(a, b);
}
else
{
yue=maxyue(b, a);
}
int bei=a*b/yue;
System.out.println(bei);
}
}
2.更相减损法
import java.util.Scanner;
public class Main
{
static int maxyue(int a,int b)
{
int temp = a - b;
while (temp!=b)
{
if (temp>b)
{
a = temp;
}
else
{
a = b;
b = temp;
}
temp = a - b;
}
return b;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int a=scanner.nextInt();
int b=scanner.nextInt();
int yue;
if (a>b)
{
yue=maxyue(a, b);
}
else
{
yue=maxyue(b, a);
}
int bei=a*b/yue;
System.out.println(bei);
}
}
Python实现
1. 辗转相除法
def maxyue(a, b):
while (a%b):
temp=a
a=b
b=temp%b
return b
a,b=map(int,input().split())
if (a>b):
yue=maxyue(a, b)
else:
yue=maxyue(b, a)
print( int(a * b / yue))
2.更相减损法
def maxyue(a, b):
temp = a - b
while (temp!=b):
if (temp>b):
a = temp
else:
a = b
b = temp
temp = a - b
return b
a,b=map(int,input().split())
if (a>b):
yue=maxyue(a, b)
else:
yue=maxyue(b, a)
print( int(a * b / yue))