Java求两个正整数的最大公约数和最小公倍数
更新时间:2017年02月21日 22:24:32 投稿:mdxy-dxy
这篇文章主要介绍了输入两个正整数m和n,求其最大公约数和最小公倍数,需要的朋友可以参考下
题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
程序分析:利用辗除法。
最大公约数:
public class CommonDivisor{
public static void main(String args[])
{
commonDivisor(24,32);
}
static int commonDivisor(int M, int N)
{
if(N<0||M<0)
{
System.out.println("ERROR!");
return -1;
}
if(N==0)
{
System.out.println("the biggest common divisor is :"+M);
return M;
}
return commonDivisor(N,M%N);
}
}
最小公倍数和最大公约数:
import java.util.Scanner;
public class CandC
{
//下面的方法是求出最大公约数
public static int gcd(int m, int n)
{
while (true)
{
if ((m = m % n) == 0)
return n;
if ((n = n % m) == 0)
return m;
}
}
public static void main(String args[]) throws Exception
{
//取得输入值
//Scanner chin = new Scanner(System.in);
//int a = chin.nextInt(), b = chin.nextInt();
int a=23; int b=32;
int c = gcd(a, b);
System.out.println("最小公倍数:" + a * b / c + "\n最大公约数:" + c);
}
}
大家可以参考脚本之家以前发布的文章。
相关文章
如何解决Could not transfer artifact org.spri
在Maven更新过程中遇到“Could not transfer artifact org.springframework.boot”错误通常是由于网络问题,解决方法是在Maven的设置中忽略HTTPS,添加特定语句后,可以正常下载依赖,但下载速度可能较慢,这是一种常见的解决方案,希望对遇到相同问题的人有所帮助2024-09-09
Springboot项目实现Mysql多数据源切换的完整实例
这篇文章主要给大家介绍了关于Springboot项目实现Mysql多数据源切换的完整实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-11-11


最新评论