Hi,
So on Project Euler the Problem 4 states the following:
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.
I have tried the following:
#include <stdio.h>
#include <stdlib.h>
int check(int result)
{
char b[7];
sprintf(b, "%d", result);
if (b[0] == b[5] && b[1] == b[4] && b[2] == b[3])
{
return 1;
}
else
{
return 0;
}
}
int main () {
int i;
int g;
int final;
for (i = 999; i > 99; i--)
{
for (g = 999; g > 99; g--)
{
if (check(g*i) == 1)
{
final = g*i;
goto here;
}
}
}
here:
printf("%d", final);
}
But, this does not work. Instead of the right answer, I get 580085, which I guess is a palindrome at least, but still not the right answer.
Let me explain my program starting from int main
:
int i
andint g
are my multipliers. They are those two three digit numbers.int final
is the number that will store the largest palindrome.- I start two for loops going to down to get every number possibility.
- I get out of the loop using a goto when the first palindrome is reached(probably should not but, it doesn't effect a small program like this too much).
- The first palindrome should be the biggest one possible since I am counting down from the top.
Let me now explain my check:
- First off since these are two three digit numbers multiplying together to determine the size a char would need to be to hold that value I went to a calculator and multiplied 999 * 999 and it ended up being 6 then I need to add one because I found out from one the questions I posted earlier that
sprintf
puts a\0
character at the end. - Ok, now that I have a char and all, I copied
result
(whichi*g
inint main
) and put it inchar b[7]
. - Then I just checked
b
to see if it equalled it self with by hard coding each slot I needed to check for. - Then I returned accordingly, 1 for true, and 2 for false.
This seems perfectly logical to me but, it does not work for some weird reason. Any hints?