[Euler]Problem 32 - Pandigital products

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.

公式 a * b = c;

一共9个数, 所以推算c只能是4位数, a是1到4位, b是1到2位。

至于a, b , c是否是pandigital products, 没费脑子一位一位的算,直接转成List,接着排序。

于是暴力的方法就这么产生了:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PandigitalProducts {

	public static void main(String[] args) {
		long before = System.currentTimeMillis();

		new PandigitalProducts().calculate();

		System.out.println("elapsed time is : " + (System.currentTimeMillis() - before));
	}

	private void calculate() {
		List<Integer> products = new ArrayList<Integer>();
		int product = 0;
		int sum = 0;

		for (int i = 1; i < 9999; i++) {

			for (int j = 1; j < 99; j++) {
				product = i * j;

				if (isPandigital(i, j, product) && !products.contains(product)) {
					products.add(product);
					sum += product;
					System.out.println("i = " + i + " , j = " + j + " , product = " + product);
				}
			}

		}

		System.out.println("sum of all products is : " + sum);
	}

	private boolean isPandigital(int a, int b, int product) {
		List<String> numberList = new ArrayList<String>();
		String idealStr = "123456789";
		String whatWeGotStr = "";

		String temp = "" + a + b + product;

		String[] strArr = temp.split("");

		for (String s : strArr) {
			numberList.add(s);
		}

		Collections.sort(numberList);

		for (String s : numberList) {
			whatWeGotStr += s;
		}

		if (whatWeGotStr.equals(idealStr)) {
			return true;
		}

		return false;
	}

}

console :

i = 138 , j = 42 , product = 5796
i = 157 , j = 28 , product = 4396
i = 159 , j = 48 , product = 7632
i = 186 , j = 39 , product = 7254
i = 198 , j = 27 , product = 5346
i = 1738 , j = 4 , product = 6952
i = 1963 , j = 4 , product = 7852
sum of all products is : 45228
elapsed time is : 2099

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值