每天一个java小程序-6

 JAVA练习题,能做多少就做多少。http://bbs.csdn.net/topics/110067294


这个是从CSDN看到的。每天一个吧 。

【程序6】 
题目:输入两个正整数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,所以很蛋疼的中间转换了一次。。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值