Oxaric’s Blog

A compendium of amazing things…

Euler Project Problem #4 Solution

Posted by oxaric on November 24, 2008

It uses C.


Click to directly download euler-solution-4.c

// filename 'euler-solution-4.c'
// By: Louis Casillas, oxaric@gmail.com

// Euler Problem #4
// Find the largest palindrome made from the product of two 3-digit numbers

#include <stdio.h>

int mypow( int num, int degree )
{
   int result = 1;

   int i;
   for ( i = 0; i < degree; i++ )
   {
      result *= num;
   }

   return result;
}

int isAPalindrome( int num )
{
   int num_of_digits = 0;
   int original_num = num;
   int temp = original_num;

   while( temp > 0 )
   {      
      temp = temp / 10;
      num_of_digits++;
   }
   
   temp = original_num;   
   
   int first_digit;
   int last_digit;

   while( num_of_digits > 1  )
   {
      first_digit = temp - ((temp / 10) * 10);
      last_digit = temp / mypow( 10, num_of_digits - 1);
      
      if ( first_digit != last_digit   )
      {
         return 0;
      }
      
      // cut off largest digit
      temp = temp - (mypow( 10, num_of_digits - 1) * first_digit);
      // cut off smallest digit
      temp /= 10;

      num_of_digits -= 2;
   }

   return 1;
}

#define MAX_MULTIPLIER 9999

int main()
{
   int num1;
   int num2;
   int largest_palindrome = 0;
   int temp = 0;

   int largest_num1 = 0;
   int largest_num2 = 0;

   for ( num1 = MAX_MULTIPLIER; num1 > 99 && (num1 * MAX_MULTIPLIER) > largest_palindrome; num1-- )
   {
      for ( num2 = MAX_MULTIPLIER; num2 > num1 && (num2 * MAX_MULTIPLIER) > largest_palindrome; num2-- )
      {   
         temp = num1 * num2;

         if ( isAPalindrome( temp ) )
         {
            if ( temp > largest_palindrome )
            {
               largest_palindrome = temp;
               largest_num1 = num1;
               largest_num2 = num2;
            }
         }
      }
   }
   
   printf( "\nSolution: %d made by %d x %d \n", largest_palindrome, largest_num1, largest_num2 ); 
}

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>