plumber plumber -4 years ago 95
C Question

Project Euler 4 - 5 digits palindrome

I have to solve problem 4 on Project Euler site for my homework:

Largest palindrome product

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.

#include <stdio.h>
int main()
{
int i,j,palindrome[1000],n,temp,k=0,num[10],max,digits;
for(i=999;i>=320;i--)
{
for(j=999;j>=320;j--)
{
n=i*j;
temp=n;
digits=0;
do
{
num[digits]=temp%10;
temp/=10;
digits++;
}
while(temp!=0);
if(num[0]==num[5] && num[1]==num[4] && num[2]==num[3])
{
palindrome[k]=n;
k++;
}
}
}
max=palindrome[0];
for(i=1;i<k;i++)
{
if(palindrome[i]>=max)
max=palindrome[i];
}
printf("%d\n",max);
}


I have got correct answer, but my code only work for number with 6 digits and it should check numbers from 100*100 (10000, 5 digits) to 999*999 (998001, 6 digits).

My code check from 320*320 to 999*999.

So can it be repaired to work with 5 digits or should I leave it like that?

Answer Source

Change inner loop to do digits/2 tests.

With num[10], the number of digits can be 1 to 10.

        // As int is good to _at least_ 32k, use long
        // long is good to _at least_ 2M
        long n = (long)i * j;
        long temp = n;

        do {
          ...
        } while(temp!=0);

        bool same = true; 
        for (int a=0; a<digits/2; a++) {
          if (num[a] != num[digits-1-a]) same = false;
        }
        if (same) {
            palindrome[k]=n;
            k++;
        }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download