Euler #4
Published on Thursday, July 21, 2011Next up in Project Euler was a question about palindromic numbers, specifically those that are the product of two three-digit numbers. The text of the problem in its entirety is below.
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.
I set out to write a few lines of brute-force code, but the palindromer() ended up being pretty long. The whole program ran in a flash (way faster than what I wrote for problem #3), though, so I guess I didn't waste too much processing power on this problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Problem4
{
class Program
{
static void Main(string[] args)
{
int biggest = 10001;
int product;
for (int i = 100; i < 1000; i++)
{
for (int j = 100; j < 1000; j++)
{
product = i * j;
if (palindromeTester(product) && (product > biggest)) { biggest = product; }
}
}
Console.WriteLine(biggest);
}
private static bool palindromeTester(int product)
{
int palindrome = palindromer(product);
if (palindrome == product) { return true; }
else { return false; }
}
private static int palindromer(int product)
{
int invers = 0;
int[] bouleverseur = new int[6];
bouleverseur[5] = (product / 100000);
product -= bouleverseur[5] * 100000;
bouleverseur[4] = (product / 10000);
product -= bouleverseur[4] * 10000;
bouleverseur[3] = (product / 1000);
product -= bouleverseur[3] * 1000;
bouleverseur[2] = (product / 100);
product -= bouleverseur[2] * 100;
bouleverseur[1] = (product / 10);
product -= bouleverseur[1] * 10;
bouleverseur[0] = (product);
invers = bouleverseur[5]
+ bouleverseur[4] * 10
+ bouleverseur[3] * 100
+ bouleverseur[2] * 1000
+ bouleverseur[1] * 10000
+ bouleverseur[0] * 100000;
if (bouleverseur[5] == 0) { invers /= 10; }
return invers;
}
}
}