Solving Project Euler 38 with MATLAB: The Vectorized Pandigital Blitz

Solving Project Euler 38 with MATLAB: The Vectorized Pandigital Blitz


tags:

  • Project Euler
  • MATLAB
  • Pandigital Numbers
  • Performance Optimization
  • Vectorization
    excerpt: "In this post, we continue our exploration of the Largest Pandigital Concatenated Product problem, this time using MATLAB. Learn how we vectorized the entire search and uncovered the largest pandigital number using concise and fast matrix operations."

This post is part of a multi-language series exploring the problem of finding the largest 1–9 pandigital concatenated product. Check out the C# and Python editions too.

Why MATLAB?

MATLAB might not be the first language that comes to mind for algorithmic problem solving, but its strength in matrix manipulation and vectorized computation makes it a powerful ally for concise, high-performance numeric routines.

In this post, we'll look at a highly optimized and readable MATLAB script that solves Project Euler Problem 38 by leveraging vectorized operations instead of loops.


Problem Recap

Find the largest 1–9 pandigital number that can be formed as the concatenated product of an integer with (1,2,...,n) where n > 1.

We already know from analysis (see previous posts) that the maximum pandigital number will be found with n = 2.

The MATLAB Way

Step 1: Generate All Base Candidates

k = (1:9999)';                % All 1- to 4-digit numbers
p2 = 2 * k;                   % Compute 2×k
d2 = floor(log10(p2)) + 1;    % Count digits in 2×k
shift = 10.^d2;               % Precompute power of 10 to concatenate
concat = k .* shift + p2;     % Create k||2k concatenated number

This is MATLAB’s power: we operate on entire vectors at once.

Step 2: Filter by Digit Count

We’re only interested in 9-digit numbers:

mask9 = (concat >= 1e8) & (concat < 1e9);
cands9 = concat(mask9);
k9 = k(mask9);

Step 3: Check for Pandigitality

Convert each candidate to a 9-character string, sort the digits, and check if it matches "123456789".

strs = compose('%09d', cands9);
C = char(strs);
sortedC = sort(C, 2);
isPan = all(sortedC == repmat('1':'9', size(sortedC,1),1), 2);

This is vectorized string checking, MATLAB-style.

Step 4: Extract the Max

panVals = cands9(isPan);
panKs = k9(isPan);
[maxVal, idx] = max(panVals);

Step 5: Print the Result

fprintf('Largest 1–9 pandigital concatenated product: %d  (k = %d, n = 2)\n', ...
        maxVal, panKs(idx));

Why It Works

We limit ourselves to n = 2 since it's been mathematically shown that higher n values can't produce larger results due to digit overflow. From there, vectorization takes care of performance.

Performance Notes

This code runs almost instantly. MATLAB’s JIT and native support for array math make it highly efficient even on large candidate sets.

Conclusion

If you thought MATLAB wasn’t suited for algorithmic puzzles, think again. With the right approach, MATLAB can be a top-tier choice for numeric problem solving.

Stay tuned for the final post in the series, where we’ll wrap up our cross-language comparison and look at profiling and benchmarking across implementations.


☑️ Try this code in your own MATLAB environment and let us know how it performs on your machine.

📁 You can find the full code snippet in the GitHub repository.