每天一个java小程序-4

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


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

【程序4】 
题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 
程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成: 
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。 
(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。 
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。 

其实就是除质数,直到除不尽。

===== Main.java =====
package main;

import dec.DecNum;

public class Main {

public static void main(String[] args) {
int num = 0;
DecNum decNum;

if (args.length == 0) {
System.out.println("No input value");
return;
}

try {
num = new Integer(args[0]);
} catch (NumberFormatException e) {
System.out.println("Input value not a integer");
return;
}

decNum = new DecNum(num);

decNum.decNum();
decNum.printDecNum();
}
}

======== DecNum =======
package dec;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class DecNum {
public DecNum(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;
}
}
decNumList.add(num);
}

public void printDecNum() {
Iterator it = decNumList.iterator();

while (it.hasNext()) {
int tmp = it.next();
System.out.println(tmp);
}
}

private int num;
private List decNumList;
private static List primeList;
}


前几个题也总是质数的问题,所以有些代码可以复用了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值