Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Code seems perfect?

Status
Not open for further replies.

adu

Programmer
Joined
Apr 24, 2002
Messages
2
Location
CA
Okay, basically what I have to do is find the products of X times Y, where X and Y are integers which are greater than 0 and less than 1000.
From these products find the sum of any which are palindromes.

My code which is included below seems fine with me, however I keep getting a wrong answer (393705315), I was told the correct answer is a nine digit number starting with a 5. Anything wrong with the code?

------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

long int prod,sum;
int x,y,q,z,len;
char store[7],reverse[7];

int main() {

sum=0;

for (x=1; x<1000; x++) {
for (y=1; y<1000; y++) {
prod = x*y;
itoa(prod,store,10);
len = strlen(store);
q = 0;
for (z=(len-1); z>=0; z--) {
reverse[q] = store[z];
q++;
}
if (atoi(store) == atoi(reverse)) {
sum = sum + (x*y);
}
}

}
printf(&quot;Done. %d&quot;,sum);
getch();
return 0;
}
--------------------------------------
 
Hi.

Try this:

...
for(z=(len-1);z>=0;z--)
{
reverse[q] = store[z];
q++;
}
reverse[q] = '\0';
...

best regards,

Kirilla
 
You should use for store and reverse at least 20 Bytes.
 
Hi.

The problem is starting after the first Y cycle.

When X = 1 and Y = 999
then there is 999\0 is in the store buffer and
999EEEE999 in the reverse buffer.
Because EEEE is not a number atoi translate only the number part of reverse or until \0 (NULL CHAR)
The n ext step
X = 2 and Y =1 then
there is 2\0 in the store buffer and
299EEEEE2 in the reverse buffer because NULL CHAR is not copied.
I put it manually with revese[q] = '\0'; (look above)
and it is working.

best regards,

Kirilla
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top