最大公约和最小公倍数
2015-09-04 09:55
260 查看
package basic40;
import java.util.Scanner;
public class CommonDivisor {
public static int CommonDiv(int a, int b){
int max = a > b ? a : b;
int min = a < b ? a: b;
while (max % min != 0){
int temp = max % min;
max = min;
min = temp;
}
return min;
}
public static int CommonMultiple(int a, int b){
int commonDivisor = CommonDiv(a, b);
int aa = a / commonDivisor;
int bb = b / commonDivisor;
return commonDivisor * aa * bb;
}
public static void main(String args[]){
Scanner sc = new Scanner (System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println( "CommonDivisor is:" + CommonDiv (a, b));
System.out.println("CommonMultiple is:" + CommonMultiple(a, b));
}
}
注意:
1.一开始要判断输入的数的情况:若为负数;若有为0的数, 需要return -1
2.求最大公约数更简便的写法:
public static int gcd(int m, int n)
{
while (true)
{
if ((m = m % n) == 0)
return n;
if ((n = n % m) == 0)
return m;
}
}
3.最小公倍数的另一种求法
a * b / c
4.while(true)的用法:
import java.util.Scanner;
public class CommonDivisor {
public static int CommonDiv(int a, int b){
int max = a > b ? a : b;
int min = a < b ? a: b;
while (max % min != 0){
int temp = max % min;
max = min;
min = temp;
}
return min;
}
public static int CommonMultiple(int a, int b){
int commonDivisor = CommonDiv(a, b);
int aa = a / commonDivisor;
int bb = b / commonDivisor;
return commonDivisor * aa * bb;
}
public static void main(String args[]){
Scanner sc = new Scanner (System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println( "CommonDivisor is:" + CommonDiv (a, b));
System.out.println("CommonMultiple is:" + CommonMultiple(a, b));
}
}
注意:
1.一开始要判断输入的数的情况:若为负数;若有为0的数, 需要return -1
2.求最大公约数更简便的写法:
public static int gcd(int m, int n)
{
while (true)
{
if ((m = m % n) == 0)
return n;
if ((n = n % m) == 0)
return m;
}
}
3.最小公倍数的另一种求法
a * b / c
4.while(true)的用法:
用法?问的好奇怪。while都是用来循环么。循环终止条件写true,这种情况,是需要在循环内主动终止循环的,要么使用return返回,要么使用break跳出循环。 用在哪里呢?比如socket连接,服务端就需要一直等到客户端输入啊响应啊这么样的。还有很多其他的情况呢。需要你慢慢去发掘。
相关文章推荐
- stl string
- webService(php)的soap与nusoap服务端与客户端的通信
- python 错误集
- 被动DNS
- 新兵训练营系列课程——Feed架构介绍 - 长微博
- CentOS7图形界面切换及版本查看
- 半边数据结构及其使用
- uva455 - Periodic Strings
- C++类中的常量
- Button 样式及selector选择器
- TQ2440 学习笔记—— 21、中断体系结构
- 【笔试】41、二叉搜索树的后序遍历列
- 我是菜鸟:concurrentHashMap实现原理
- 推送机制
- activemq 入门
- Android WakeLock使用方法
- 无法解析的外部符号__imp__AlphaBlend@44
- Android实战简易教程-第五十一枪(ListView实现子控件的动态显示和隐藏、checkbox全选和反选)
- 根据传入的两个参数,做分隔更新数据库中的值。
- 剑指offer:二维数组中的查找