project euler 32

来源:互联网 发布:数字滚动抽奖软件 编辑:程序博客网 时间:2024/05/21 00:14

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.


全数字的乘积

如果一个n位数包含了1至n的所有数字恰好一次,我们称它为全数字的;例如,五位数15234就是1至5全数字的。

7254是一个特殊的乘积,因为在等式39 × 186 = 7254中,被乘数、乘数和乘积恰好是1至9全数字的。

找出所有被乘数、乘数和乘积恰好是1至9全数字的乘法等式,并求出这些等式中乘积的和。

注意:有些乘积可能从多个乘法等式中得到,但在求和的时候只计算一次。

package projecteuler;import java.util.HashSet;import java.util.Set;import org.junit.Test;public class Prj32 {/** * 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. */@Testpublic void test() {// System.out.println(9 * 9999);// System.out.println(10 * 999);// System.out.println(99 * 999);System.out.println(Calculator.calculate());}public static class Calculator {/** * a + b + c = 9; a = 1 && b = 4; a = 2 && b = 3; *  * @return */public static int calculate() {int a = 0;int b = 0;Set<Integer> set = new HashSet<Integer>();for (a = 1; a <= 10; a++) {for (b = 1000; b <= 10000; b++) {if (checkNum(a, b, a * b)) {System.out.println(a + "*" + b + "=" + a * b);set.add(a * b);}}}for (a = 10; a <= 100; a++) {for (b = 100; b <= 1000; b++) {if (checkNum(a, b, a * b)) {System.out.println(a + "*" + b + "=" + a * b);set.add(a * b);}}}int sum = 0;for (Integer intVal : set) {sum += intVal;}return sum;}public static boolean checkNum(int a, int b, int c) {Set<Integer> set = new HashSet<Integer>();int val = a;while (val >= 10) {if (set.contains(val % 10)) {return false;}set.add(val % 10);val /= 10;}if (set.contains(val)) {return false;}set.add(val);val = b;while (val >= 10) {if (set.contains(val % 10)) {return false;}set.add(val % 10);val /= 10;}if (set.contains(val)) {return false;}set.add(val);val = c;while (val >= 10) {if (set.contains(val % 10)) {return false;}set.add(val % 10);val /= 10;}if (set.contains(val)) {return false;}set.add(val);return set.size() == 9 && set.contains(1) && set.contains(2)&& set.contains(3) && set.contains(4) && set.contains(5)&& set.contains(6) && set.contains(7) && set.contains(8)&& set.contains(9);}}}


0 0