JAVA练习题,能做多少就做多少。http://bbs.csdn.net/topics/110067294
这个是从CSDN看到的。每天一个吧 。
【程序6】
题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
1.程序分析:利用辗除法。
题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
1.程序分析:利用辗除法。
我用的还是求素数的方法
==== Main.java ====
package main;
import common.Common;
import num.Num;
public class Main {
public static void main(String[] args) {
Num num1 = new Num(100);
Num num2 = new Num(90);
Common func = new Common();
num1.decNum();
num2.decNum();
func.cntValue(num1.getDecNumList(), num2.getDecNumList());
System.out.println("Greate div mum is " + func.getGreateDiv());
System.out.println("Least mul mum is " + func.getLeastMul());
}
}
==== Num.java ====
package num;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Num {
public Num(int num) {
this.num = num;
if (primeList == null) {
primeList = new ArrayList();
primeList.add(2);
primeList.add(3);
initPrimeList();
}
}
private static void initPrimeList() {
int i;
boolean isPrime = true;
for (i = 3; i <= 1000; i++) {
Iterator it = primeList.iterator();
while (it.hasNext()) {
int tmp = (int) it.next();
if ((i % tmp) == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primeList.add(i);
} else {
isPrime = true;
}
}
}
public void decNum() {
Iterator it = primeList.iterator();
if (decNumList == null) {
decNumList = new ArrayList();
}
while (it.hasNext()) {
int tmp = it.next();
while ((num % tmp) == 0) {
decNumList.add(tmp);
num = num / tmp;
}
}
if (num != 1)
decNumList.add(num);
}
public List getDecNumList() {
return decNumList;
}
private int num;
private List decNumList;
private static List primeList;
}
==== Common.java ====
package common;
import java.util.Iterator;
import java.util.List;
public class Common {
public void cntValue(List list1, List list2) {
greateDiv = 1;
leastMul = 1;
Iterator it = list1.iterator();
while (it.hasNext()) {
int tmp = it.next();
if (list2.contains(tmp)) {
greateDiv = greateDiv * tmp;
list2.remove(list2.indexOf(tmp));
} else {
leastMul = leastMul * tmp;
}
}
it = list2.iterator();
while (it.hasNext()) {
int tmp = it.next();
leastMul = leastMul * tmp;
}
leastMul = leastMul * greateDiv;
}
public int getGreateDiv() {
return greateDiv;
}
public int getLeastMul() {
return leastMul;
}
private int greateDiv;
private int leastMul;
}
太晚了。。。所以,算是充数的吧。。。写的不咋地。。
list2.remove(list2.indexOf(tmp));
这个,本来是可以直接remove(object)的,但是恰好我的object就是int,导致remove的参数成了index,所以很蛋疼的中间转换了一次。。。。