In this question, would dig be 2 inputs, such as 91 and 99? And lim can be any number the user calls?
5 views (last 30 days)
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.)
Stephen23 on 7 Sep 2017
Edited: Stephen23 on 7 Sep 2017
I know that this is homework, but someone needed to demonstrate how this can be done quite simply, without using slow and unnecessary third-party functions: I believe that champions2015 and future readers deserve to be shown that MATLAB code can be neat, efficient, and straightforward. Note that this code actually does exactly what the question asks for!
function n = palin_product(dig,lim)
n = 0;
V = 10.^dig-1:-1:10.^(dig-1);
for k1 = V
for k2 = V
p = k1*k2;
if p>n && p<lim
s = sprintf('%d',p);
n = p;
ans = 9009
ans = 8448
ans = 8118
ans = 8008
ans = 7227
More Answers (3)
the cyclist on 6 Sep 2017
I would interpret it as follows.
You are trying to find p1 * p2 = n.
- lim is any number the user chooses (just as you guessed). The output, n, must be smaller than lim.
- dig is the number of digits that p1 and p2 each have. For example, if p1=91, and p2=99, then dig=2, because they are 2-digit numbers.
John BG on 7 Sep 2017
Edited: Jan on 25 Feb 2018
this is John BG <mailto:firstname.lastname@example.org email@example.com>
the following is a slight variation of what's been asked, this function
- returns the nearest palindrome to the input
- also calculates the 2 numbers of digit length dig that multiplied are lim
- if the input is already a palindrome, it decomposes as requested lim, not seeking any smaller palindrome.
function [lim r1 r2]=palin_product(dig,lim2)
lim=lim2 % keep start value in lim2, modify lim
while ~ispal % find next symmetric integer below input lim2
while L1(n1)==L1(n2) && n1<=floor(length(L1)/2)
if L1(n1)==L1(n2) ispal=1; end
if ~ispal lim=lim-1; end
s1=10^(dig-1);s2=str2num(repmat('9',1,dig)); % find whether found lim can be decomposed
while ~(s1*s2==lim) && p<length(L)
if p<=length(L) && s1*s2==lim
if r1==0 && r2==0
end % function
the most recent version of the function combinator and its support functions are all packed and freely available from
combinator_update.zip and palin_product.m are both attached to this answer.
If you find this answer useful would you please be so kind to consider marking my answer as Accepted Answer?
To any other reader, if you find this answer useful please consider clicking on the thumbs-up vote link
thanks in advance
[EDITED: Copyrighted code removed]