A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
    Not too hard. I tried to this a bit different and more optimized than when I did this problem in C++ so here's what I came out with:
#include <stdio.h>
#include <string.h>
int isPalindrome(const int *pTest)
{
char string[6];
int length=0;
sprintf(string, "%d", (*pTest) );
length=strlen(string);
switch(length)
{
case 5:
if(string[0]==string[4] && string[1]==string[3])
return 1;
case 6:
if(string[0]==string[5]&&string[1]==string[4]&&string[2]==string[3])
return 1;
default:
return 0;
}; //End of switch statment
return 0;
}
int main()
{
int test=0;
int *pTest=&test;
int highest=0;
int *pHighest=&highest;
int i=0;
int j=0;
for(i=1000; i>100; i--)
{
for(j=1000; j>100; j--)
{
test=i*j;
if(isPalindrome(pTest) && (*pTest)>(*pHighest) )
{
highest=i*j;
}
}
}
printf("%d\n", highest);
return 0;
}
Execution Time: 0.485 s
    So what I did was had 2 nested for loops and sent the product of the two ints (i and j) to the function isPalindrome() Then I used sprinf() to change the int to a string which I found the length of and checked if it was a palindrome or not.
    So there you have it, Project Euler problem 4.
       NotMyFault
No comments:
Post a Comment