Solution to Project 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.
Updated: June 4, 2023 — Training Time: 2 minutes
Overseen by: Archangel Macsika
All Training Resources
Scroll for more menu list
Topic: Project Euler Problem 32: Pandigital products.
Difficulty: Easy.
Objective: 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.
Input: None.
Expected Output: 45228.
Sikademy Solution in Java Programming Language
package sikademy;
/**
*
* @author Archangel Macsika
* Copyright (c) Sikademy. All rights reserved
*/
import java.util.Arrays;
public class SikademyEulerSolution {
public String run() {
int sum = 0;
for (int i = 1; i < 10000; i++) {
if (hasPandigitalProduct(i))
sum += i;
}
return Integer.toString(sum);
}
private static boolean hasPandigitalProduct(int n) {
// Find and examine all factors of n
for (int i = 1; i <= n; i++) {
if (n % i == 0 && isPandigital("" + n + i + n/i))
return true;
}
return false;
}
private static boolean isPandigital(String s) {
if (s.length() != 9)
return false;
char[] temp = s.toCharArray();
Arrays.sort(temp);
return new String(temp).equals("123456789");
}
public static void main(String[] args) {
SikademyEulerSolution solution = new SikademyEulerSolution();
System.out.println(solution.run());
}
}
Sikademy Solution in Python Programming Language
#
# @author Archangel Macsika
# Copyright (c) Sikademy. All rights reserved.
#
def compute():
ans = sum(i for i in range(1, 10000) if has_pandigital_product(i))
return str(ans)
def has_pandigital_product(n):
# Find and examine all factors of n
for i in range(1, sqrt(n) + 1):
if n % i == 0:
temp = str(n) + str(i) + str(n // i)
if "".join(sorted(temp)) == "123456789":
return True
return False
def sqrt(x):
assert x >= 0
i = 1
while i * i <= x:
i *= 2
y = 0
while i > 0:
if (y + i)**2 <= x:
y += i
i //= 2
return y
if __name__ == "__main__":
print(compute())