I’m trying to make a function that finds the largest palindrome made of 3-digit factors. When I run the code, it finds a palindrome, but it’s not the largest. Don’t criticize my code, especially the goto, as I’m pretty new to C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int isPalindrome(int number) {
int palindrome = 1;
char *str = (char *)malloc(8 * sizeof(char));
sprintf(str, "%d", number);
int len = strlen(str);
for (int i = 0; i < len; i++) {
if ((str[i] == str[len - (i+1)]) && palindrome) continue;
else palindrome = 0;
}
free(str);
return palindrome;
}
int main(void) {
char* omg = "xF0x9Fx98xB2";
int factorI = 0;
int factorJ = 0;
for (int i = 999; i >= 100; i--) {
for (int j = 999; j >= 100; j--) {
if (isPalindrome(i * j)) {
factorI = i;
factorJ = j;
goto end_loop;
}
}
}
end_loop: printf("Done! Found palindrome. (%s%s%s)n", omg, omg, omg);
printf("i: %dnj: %dn", factorI, factorJ);
printf("PALINDROME: %d", factorI * factorJ);
printf("nnHello Worldn");
return 0;
}
When I run the code, I get this:
Done! Found palindrome. (????????????)
i: 995
j: 583
PALINDROME: 580085
Hello World
But that doesn’t seem to be the biggest palindrome, because when I enter it into Project Euler, it marks the solution as incorrect. Can anyone help debug my code and see where I messed up? I looked over it like three times and I found nothing. PLEASE don’t tell me the correct factors/palindrome, just help me with my code.