Project Euler
Problem 32(Pandigital products)
(이경수)
2019. 5. 19. 13:35
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.
In Python:
#PE32 Pandigital products
import time
import math
def ispandigit(n):
nList = list(str(n))
nList.sort()
for i in range(0, 9):
if i + 1 != int(nList[i]):
return False
return True
startTime = time.time()
resultList = []
for n in range(0, 2):
for i in range(10 ** n, 10 ** (n + 1)):
for j in range(10 ** (3 - n), 10 ** (4 - n)):
k = i * j
if k < math.pow(10, 4):
if ispandigit(int(str(i) + str(j) + str(k))) is True:
resultList.append(k)
print(sum(set(resultList)))
print(time.time() - startTime, "seconds")
Run time: 0.2201831340789795 seconds
In Java:
//Euler32 Pandigital products
package project_euler31_40;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Collections;
public class Euler32 {
public static Boolean ispandigit(int n) {
String nStr = Integer.toString(n);
String data[];
ArrayList<Integer> nList = new ArrayList<Integer>();
data = nStr.split("");
for (int i = 0; i < nStr.length(); i++) {
nList.add(Integer.parseInt(data[i]));
}
Collections.sort(nList);
for (int i = 0; i < 9; i++) {
if (nList.get(i) != i + 1) {
return false;
}
}
return true;
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int result = 0;
HashSet<Integer> resultList = new HashSet<Integer>();
for(int n = 0; n < 2; n++) {
for (int i = (int) Math.pow(10, n); i < (int) Math.pow(10, n + 1); i++) {
for (int j = (int) Math.pow(10, 3 - n); j < (int) Math.pow(10, 4 - n); j++) {
int k = i * j;
if (k < Math.pow(10, 4)) {
if (ispandigit(Integer.parseInt(
Integer.toString(i)+Integer.toString(j)+Integer.toString(k)
)) == true) {
resultList.add(k);
}
}
}
}
}
for (int n : resultList) {
result += n;
}
System.out.println(result);
long endTime = System.currentTimeMillis();
System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");
}
}
Run time: 0.303seconds
Solution: 45228