Created
December 6, 2012 22:24
-
-
Save juanfal/4229047 to your computer and use it in GitHub Desktop.
Largest palindrome built with n digits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 004.palindromeLargest.cpp | |
// juanfc 2012-06-24 | |
// A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. | |
// Find the largest palindrome made from the product of two 3-digit numbers. | |
#include <iostream> | |
using namespace std; | |
const int NOOFDIGITS = 3; | |
bool isPalind(int); | |
int main() | |
{ | |
// find the limits | |
int baseTop = 1; | |
for (int i = 0; i < NOOFDIGITS; ++i) { | |
baseTop *= 10; | |
} | |
int baseBot = baseTop / 10; | |
int greatestPal = 0; | |
int ii, jj; | |
int test; | |
for (int i = baseTop-1; i >= baseBot; i--) { | |
for (int j = baseTop-1; j >= i; j--) { | |
test = i * j; | |
if (isPalind(test) and test > greatestPal) { | |
greatestPal = test; | |
ii = i; | |
jj = j; | |
} | |
} | |
} | |
if ( greatestPal == 0 ) | |
cout << "None" << endl; | |
else | |
cout << greatestPal << ": " << ii << "x" << jj << endl; | |
return 0; | |
} | |
bool isPalind(int a) | |
{ | |
// here you need to convert the int to its decimal string chars | |
// it can be done several ways: | |
char s[24]; | |
sprintf(s, "%d", a); | |
int i = 0; | |
int j = 0; | |
// length | |
while (s[j] != '\0') | |
j++; | |
--j; // last char | |
while (i < j and s[i] == s[j]) { | |
++i; | |
--j; | |
} | |
return i >= j; | |
} | |
// 1: 9: 3x3 | |
// 2: 9009: 91x99 | |
// 3: 906609: 913x993 | |
// 4: 99000099: 9901x9999 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment