pdjurisic
pdjurisic

Reputation: 25

Largest palindrome product of two 3 digit numbers

It was probably already posted somewhere, since it's a project Euler problem, but, I don't have a problem solving the particular problem, though I do have a problem with a code I wrote, since I can't seem to find a mistake.

My guess is that I'm overseeing something at printing or at memorising values, but I am not certain. Anyways, here's my code:

#include <stdio.h>
#include <stdlib.h>

int main(){
int x = 999, y = 999, z = 0, w = 0, a=0, *largest = a;
for (x; x > 99; x--){
    for (y; y > 99; y--){
        z = x*y;
        while (z != 0){
            w = w * 10;
            w = w + z % 10;
            z = z/10;
        }
        if (x*y == w){
            a = w;
            goto stop;
        }
        w = 0;
    }
}
stop: printf("%d\n", largest);
system("pause");
return 0;
}

I know that a and largest and stuff aren't necessary, I was just testing a lot changing all kind of stuff, using pointers and what so not, so no need to pay a lot of attention to that part of the code.

Upvotes: 1

Views: 63

Answers (4)

user3629249
user3629249

Reputation: 16540

the posted code fails to cleanly compile.

Suggest always enabling all warnings when compiling

(for gcc, at a minimum, use '-Wall -Wextra -pedantic')

Fix the warnings, don't just try to hide them.

Then post the corrected code, if it still displays the problem

Upvotes: 0

P.P
P.P

Reputation: 121357

You code assigns the largest product's value in a but you are printing largest which is a pointer. Your program doesn't need the pointer largest at all.

Your code also doesn't work because you

  • don't check if the largest is greater than previous one
  • do not reset y to 999 in the inner loop.

With the above two fixes, it would look like:

#include <stdio.h>
#include <stdlib.h>

int main(void){
int x = 999, y = 999, z = 0, w = 0, a=0;

for (x; x > 99; x--){
    for (y=999; y > 99; y--){
        z = x*y;
        while (z != 0){
            w = w * 10;
            w = w + z % 10;
            z = z/10;
        }
        if (x*y == w && a<x*y){
            a = w;
        }
        w = 0;
    }
}
printf("%d\n", a);
return 0;
}

Upvotes: 1

Hector Colon
Hector Colon

Reputation: 11

As mentioned by rakeb, you should use: *largest = &a

Besides that, the reason you are not getting the correct answer is because your if statement is never true so 'a' will always stay 0.

Upvotes: 1

Sourav Kanta
Sourav Kanta

Reputation: 2757

First of all you are assigning a int type to a int * type in the statement

 *largest=a;

make it *largest=&a;

Moreover while printing use the * operator before largest

stop: printf("%d\n", *largest);

Finally to add up your logic may be faulty as you check :

999X999 , 999X998 , 999X997 and so on........

however 999*997 is less than 998*998 and hence your code may lead to a lower pallindrome number than possible.

Upvotes: 0

Related Questions