(7)如何得到所有的 "水仙花数" ?

本程序转载自:如何得到所有的水仙花数

感谢Android_iPhone日知己所无),preferme冰思雨)等人;


package test;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 找出所有的水仙花数
 * 判断一个数是否为水仙花数:一个N位整数,其各位数字的N次方的和等于该数本身
 *
 * @author preferme (冰思雨)
 *
 */
public class ShuiXianHuaTree {

	public static final SimpleDateFormat SDF = new SimpleDateFormat(
			"yyyy-MM--dd HH:mm:ss.SSS");
	public static final BigInteger EndPoint = new BigInteger(
			"115132219018763992565095597973971522402");
	private static final BigInteger Poison = new BigInteger("-1");

	private static class CompareThread extends Thread {
		private BlockingQueue<BigInteger> numbers;

		public CompareThread(BlockingQueue<BigInteger> queue) {
			numbers = queue;
		}

		public void run() {
			BigInteger number = BigInteger.ZERO;
			try {
				while ((number = numbers.take()) != Poison) {
					if (isNarcissisticNumber(number)) {
						System.out.println(SDF.format(new Date()) + "\t"
								+ number);
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private static final BigInteger[][] Powers = new BigInteger[40][10];
	static {
		for (int i = 0; i < 40; i++) {
			for (int j = 0; j < 10; j++) {
				Powers[i][j] = BigInteger.valueOf(j).pow(i);
			}
		}
	}

	public static boolean isNarcissisticNumber(final BigInteger number) {
		BigInteger sum = BigInteger.ZERO; // 各位数字的N次方的和
		char[] digitArray = number.toString(10).toCharArray(); // 各位数字的数组
		for (char digit : digitArray) {
			sum = sum.add(Powers[digitArray.length][digit - '0']);
		}
		return sum.compareTo(number) == 0;
	}

	public static void main(String[] args) throws InterruptedException {
		BlockingQueue<BigInteger> queue = new LinkedBlockingQueue<BigInteger>(
				1000);
		CompareThread[] pool = new CompareThread[Runtime.getRuntime()
				.availableProcessors()];
		for (int i = 0; i < pool.length; i++) {
			pool[i] = new CompareThread(queue);
			pool[i].setPriority(Thread.MIN_PRIORITY);
			pool[i].start();
		}
		System.out.println("水仙花数列表");
		for (BigInteger number = BigInteger.ZERO; number.compareTo(EndPoint) <= 0; number = number
				.add(BigInteger.ONE)) {
			queue.put(number);
		}
	}
}


转载于:https://www.cnblogs.com/xiaozhang2014/p/5297283.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值