# Largest Palindrome

**Matlab.** One of the assignments inspired by Project Euler in the Matlab course I took before . I made some simple mistakes while trying to write an efficient algorithm. There were two inputs; digit number of the integer and limit number.

For example, the answer would be 198891 for dig = 3 and lim = 200000.

**Question:** A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Write a function that is called this way: >> n = palin_product(dig,lim); The function returns the largest palindrome smaller than lim that is the product of two dig digit numbers. If no such number exists, the function returns 0. (Inspired by Project Euler.)

**Solution:** Firstly, I created a product matrix of two numbers after describing their ranges based on their digits. As a small step, function checked if square of min number is not smaller than limit or not. Limit was applied and new array was sorted from top to bottom. Then, reverse of the product array was created. As a final stage, for-loop checked if there was any palindromic number in the array. First palindromic number coming in the loop became the largest one.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function [n] = palin_product(dig,lim) tic max = 10^dig-1; %maximum number in its range min = 10^(dig-1); %minimum number in its range numbers = max : -1 : min; %range of numbers for each dig p = numbers' * numbers; %product table if min^2 >= lim %if square of min number is not smaller than lim n = 0; return end p = p(p<lim); %new product table after limit applied p = sort(p,'descend'); %sorting the array from top to bottom r = str2num(fliplr(num2str(p))); %reverse of the product for i = 1:size(p) %checking the product with its reverse if p(i) == r(i) %first palindromic number is the largest one n = p(i); toc return end end end |