0

I have succeeded in determining which two numbers when multiplied produces a numerical palindrome in C#, however I need to sort the products from lowest to highest. Is there anyway to do this?

static void LargestPalindrome()
{
    ulong product = 0;
    ulong compare = 0;
    for (uint i = 100; i < 1000; i++) 
    {
        for (uint j = 100; j < 1000; j++)
        {
            product = i * j;
            StringBuilder value = new StringBuilder(product.ToString());

            //Pass string to reverse
            string value_r = Reverse(value.ToString());

            //Check if Numeric Palindrome
            if(value_r.Equals(value.ToString()) && product>compare)
            {      
                Console.WriteLine("{0} x {1} = {2} in reverse {3}", i, j, value, value_r);
            }
        }
    }
}
w.b
  • 11,026
  • 5
  • 30
  • 49
M Coder
  • 63
  • 8

3 Answers3

1

Instead of printing out the palindrome, put the number in a List<int>. Once you've completed the loop, call list.Sort().

SecurityMatt
  • 6,593
  • 1
  • 22
  • 28
0

The following should suffice. I've simply sorted the list of palindromes and printed them to the Console screen.

static void LargestPalindrome()
{
    ulong product = 0;
    ulong compare = 0;
    List<ulong> results = new List<ulong>();
    for (uint i = 100; i < 1000; i++) 
    {
        for (uint j = 100; j < 1000; j++)
        {
            product = i * j;
            StringBuilder value = new StringBuilder(product.ToString());

            //Pass string to reverse
            string value_r = Reverse(value.ToString());

            //Check if Numeric Palindrome
            if(value_r.Equals(value.ToString()) && product>compare)
            {      
                results.Add(product);
            }
        }
    }

    results.Sort();
    foreach (var palindrome in results)
    {
        Console.WriteLine(palindrome);
    }    
}
JoshVarty
  • 9,066
  • 4
  • 52
  • 80
0

You can also use LINQ:

var palindromes = from i in Enumerable.Range(100, 9900)
                  from j in Enumerable.Range(100, 9900)
                  let product = (i * j)
                  where product.ToString() == new string(product.ToString().Reverse().ToArray())
                  orderby product
                  select product;
w.b
  • 11,026
  • 5
  • 30
  • 49