ITeye博客

素数的封装

show213 · 2013-06-22 17:22 · Java · 编程语言 · Markdown

求0-100间的素数 分析如下: 如果一个数 m ,能够被从2到 它加 1 的平方根之间的任何一个数整除了, 那么它就是一个合数, 否则, 不能被任何从2到它加 1 的平方根之间的任何一个数整除, 那么它就是一个素数。


public  boolean isZhiShu(int number) {
		// 判断是否是质数的方法
		if (number == 1) {
			return false;
		}
		for (int i = 2; i < number; i++) {
			if (number % i == 0) {
				return false;
			}
		}
		return true;
	}	



代码实现起来,并不是很难。

那现在我写个方法来把这小应用封装起来,方法参数传入最大值和最小值,返回一个数组。


public int [] ZhiShu(int min, int max){

     int data[] = new int[max];
  //中间为实现代码
     return data;
}

实现这个方法有几种思路,其中唯一的难点就是数组的大小该如何定义,如果只是像上面的代码所写填最大值,那么100个无疑对系统的巨大开销,实际上输出来的数也只有十分之三。 那有没有有几个就装几个的方法呢? 有,而且不止一种,下面来看代码

1.用List来实现:


public int[] ZhiShu(int min, int max) {
		List<Integer> list = new ArrayList<Integer>();
		Integer it = null;
		for (int i = min; i <= max; i++) {
			if (isZhiShu(i)) {
				it = new Integer(i);
				list.add(it);
			}
		}
		int data[] = new int[list.size()];
		int index = 0;
		Iterator<Integer> itr = list.iterator();

		while (itr.hasNext()) {

			Integer ite = (Integer) itr.next();
			data[index++] = ite;
		}
		return data;

	}


2.用ByteArrayOutputStream来实现.字节输出流


public byte[] ZhiShu(int min, int max) {
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		byte k[] = null;
		for (int i = min; i <= max; i++) {
			if (isZhiShu(i)) {
				bo.write(i);
			}
			k = bo.toByteArray();
		}
		return k;
	}



3.CharArrayWriter 字符输出流


public char[] ZhiShu(int min, int max) {
		CharArrayWriter bo = new CharArrayWriter();
		char k[] = null;
		for (int i = min; i <= max; i++) {
			if (isZhiShu(i)) {
				bo.write(i);
			}
			k = bo.toCharArray();
		}
		return k;
	}



以上三种方法,就满足本题的需求而言,第二种方法的效率和开销来说都是最小的,但这个方法一旦超过127就会出问题。 也许还有其它的方法,但由于本人技术实力有限,故只能想出这么多。如果有还希望读者能补充。

评论(2)

  1. #2 楼 · shenqidekobe · 2013-06-24 16:29

    参考BigInteger.ONE

  2. #1 楼 · OpenMind · 2013-06-24 13:59

    对于100以内的25个素数,如果用得很多的话,我觉得最好的方式就是静态写死在代码里面比较好。

评论功能维护中,当前仅展示历史评论。