Monday 13 April 2015

Sum of consecutive squares (Palindrome) using c#

The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 62 + 72 + 82 + 92 + 102 + 112 + 122
Find the sum of all the numbers less than limit that are both palindromic and can be written as the sum of consecutive squares


static void Main(string[] args)
        {
            Console.WriteLine("Please enter the limit");
            int limit = 100;
            limit =Convert.ToInt32(Console.ReadLine());
           
             //Find square root limit for for the number we passed to avoid unnecessary loops
            double sqrtLimit = Math.Sqrt(limit);

            long sum = 0;
            //Create list to add list of consecutive number below limit
            List<int> list = new List<int>();

            Console.WriteLine();
            Console.WriteLine("Consecutive sum of squares palindrome from 1 to " + limit);

            //loop through square root limit
            for (int i = 1; i <= sqrtLimit; i++)
            {
                //Here for example if i is 1 then j must starts from 2
               //Because we summed the value of squares like 1^1 * 2^2
                int number = i * i;
                for (int j = i + 1; j <= sqrtLimit; j++)
                {
                    number += j * j;
                    //Suppose if the sum of number cross the  limit we entered should break this loop and                          //starts from next number
                    if (number > limit) break;
                   
                    //check sum of number is palindrome or not
                    //yes then add it to list else not
                    if (IsPalindrome(number) && !list.Contains(number))
                    {                      
                        sum += number;
                        list.Add(number);
                    }
                }
            }
           
            //sort the list for alphabetical order
            list.Sort();

            foreach (var val in list)
                Console.WriteLine(val);

            Console.ReadLine();
        }

        private static Boolean IsPalindrome(int number)
        {
            //covert number to string then convert it into char array
            var revNum = number.ToString().ToCharArray();
           //reverse the array
            Array.Reverse(revNum);
            return number == Convert.ToInt32(string.Join(",", revNum).Replace(",", string.Empty));
        }