<MEMORY>Project Euler NO34

145 是一个奇怪的数字, 因为 1! + 4! + 5! = 1 + 24 + 120 = 145.
找出所有等于各位数字阶乘之和的数字之和。

注意: 因为 1! = 1 和 2! = 2 不是和的形式,所以它们不算在内。



import java.util.Arrays;

public class Problem34
{
	public static void main(String[] args)
	{
		long start = System.currentTimeMillis();
		System.out.print("answer:  ");
		
		howmany();
		
		long end = System.currentTimeMillis();
		System.out.print("time:  ");
		System.out.println(end - start);
	}
	
	static void howmany()
	{
		int total = 0;
		int array[] = new int[10];//用数组存下 0 ~ 9 的阶乘加快计算
		for (int i = 0; i <= 9; i++)
		{
			array[i] = jiecheng(i);
		}
		for (int i = 11; i <= 2540160; i++)// 9! * 7 为最大
		{
			int t = i;
			int sum = 0;
			while (t != 0)
			{
				sum += array[t % 10];
				t /= 10;
			}
			if (sum == i)
			{
				total += i;
			}
		}
		System.out.println(total);
	}
	
	static int jiecheng(int n)
	{
		int sum = 1;
		for (int i = 2; i <= n; i++)
		{
			sum *= i;
		}
		
		return sum;
	}
}



answer:  40730
time:  90

ThreadPoolTaskExecutor是Java并发包中`java.util.concurrent`下的一个组件,它用于在后台线程池中执行任务,而不是直接在主线程中运行。`submit()`方法是`ThreadPoolExecutor`中的一个重要方法,用于提交一个任务到线程池,并返回一个`Future`对象,该对象可以用来获取任务的结果或者检查任务的状态。 以下是一个简单的例子,展示了如何使用`ThreadPoolTaskExecutor`通知主线程: ```java import java.util.concurrent.*; public class Main { private static ExecutorService executor = Executors.newFixedThreadPool(5); // 创建一个固定大小的线程池 public static void main(String[] args) { Future<String> future = executor.submit(new Callable<String>() { // 使用Callable接口,它可以有返回值 @Override public String call() throws Exception { Thread.sleep(2000); // 模拟耗时操作 return "Task result"; // 返回任务结果 } }); try { // 主线程阻塞,等待任务完成 System.out.println("主线程开始等待任务结果..."); String result = future.get(); // 获取未来结果 System.out.println("任务结果: " + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } finally { // 关闭线程池,防止资源泄露 executor.shutdown(); } } } ``` 在这个例子中,`submit()`方法将`Callable`任务提交给线程池,主线程不会立即执行这个任务,而是继续运行。当`future.get()`被调用时,主线程会阻塞,直到任务完成后返回结果,或者抛出异常。`get()`方法会阻塞,直到任务完成或超时(默认无限等待)。 相关问题: 1. 为什么要使用`Future`对象来处理任务结果? 2. `Callable`和`Runnable`的区别是什么? 3. 如何设置`Future.get()`的超时时间?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值