2

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
plumber
  • 33
  • 3
  • 2
    `i*j` for larger numbers is too big for an `int` to handle; use `unsigned int` or `unsigned long long` instead. – Colonel Thirty Two Nov 05 '14 at 00:46
  • Seems duplicate question - http://stackoverflow.com/questions/24772179/largest-palindrome-product-euler-project – Blackhat002 Nov 05 '14 at 00:48
  • 1
    The palindrome array is pointless; just keep the largest you find (and record the factors to print out at the end). You should test the 5-digits numbers as well to solve the problem correctly, (but the largest obviously has 6 digits). – UncleO Nov 05 '14 at 01:06
  • @UncleO you are right this array is pointless I can just find max instead and put it in variable – plumber Nov 05 '14 at 01:37
  • You are also checking products twice needlessly. The inner loop should be `for(j=999;j>=i;j--)` – UncleO Nov 05 '14 at 02:27

1 Answers1

0

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++;
        }
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256