A palindrome reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
Deliverable
Code a solution that outputs all palindromic numbers made from the product of two 3-digit numbers.
Once complete, output a statement that tells the user the largest possible palindromic number found.
*******************************************************************************
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
usingnamespace std;
int main ()
{
int mulcon = 99;
do
{
mulcon++;
for (longint mul = 99; mul < 1000; mul++)
{
int mul2 = 99 ;
mul2++;
int reverse;
int no = mul * mul2;
int digit ;
while(no !=0)
{
digit = no%10;
reverse = reverse*10+digit;
no=no/10;
}
if ( no == reverse )
{
cout << no << endl;
}
}
} while ( mulcon < 1000 );
system ("pause");
return 0;
}
1. Where do you use mulcon? You just increase it, so the for loop is executed 900 times with the same result
2. mul2 is always 100
3. Observation: on line 16 you don't need a long int
Skipping the first part: Code a solution that outputs all palindromic numbers made from the product of two 3-digit numbers.
For the second part: Output a statement that tells the user the largest possible palindromic number found.
I remember having seen an elegant solution somewhere on the web.
#include <iostream>
#include <algorithm>
bool is_palindrome( int n ) // invariant: n is a positive six digit number
{
return n/100000 == n%10 && // first digit == last digit
(n/10000)%10 == (n/10)%10 && // second digit == fifth digit
(n/1000)%10 == (n/100)%10 ; // third digit == fourth digit
}
int main()
{
int max_so_far = 100001 ;
int first = 0 ;
int second = 0 ;
// the six digit numbers are of the form a * b,
// where a and b are three digit numbers with a <= b
// all six digit palindromes are divisible by 11
// therefore either a or b must be divisioble by 11
for( int a = 999 ; a > 99 ; --a )
{
constint min_b = std::max( max_so_far/a, a ) - 1 ;
int init_b = 999 ;
int decrement = 1 ;
if( a%11 != 0 ) // a is not divisible by 11
{
// b must be divisible by 11
init_b = 990 ;
decrement = 11 ;
}
for( int b = init_b ; b > min_b ; b -= decrement )
{
constint n = a * b ;
if( is_palindrome(n) ) // this is the largest palindrome so far
// (smaller ones are eliminated by our choice of min_b)
{
max_so_far = n ;
first = a ;
second = b ;
break ;
}
}
}
std::cout << max_so_far << " (" << first << 'x' << second << ")\n" ;
}