Saturday, August 1, 2015

calculate 1+2+…+n in C# without *,/ and keywords for, while, switch, and case, as well as a conditional operator



How do you calculate 1+2+…+n in C# without multiplication, division, key words including for, while, switch, and case, as well as a conditional operator ( A?B:C)?

using System;
using System.Linq;

namespace MiscPrograms
{
    class SumSeriesProgram
    {
        static void Main(string[] args)
        {
            int N = 5;
            Console.WriteLine("Sum for Series 1+2+... upto N={0} is {1}",
            N,SumSeries.SumSeriesElement(N));

            Console.WriteLine("Press any key to exit..");
            Console.ReadKey();

        }
    }

    public class SumSeries
    {
        //global var to hold sum
        static int Sum = 0;

        //Number of items in series
        static int NoOfItems = 0;

        //Constructor to calculate Sum value
        public SumSeries()
        {
            ++NoOfItems; Sum += NoOfItems;
        }

        //Reset global variables
        static void Reset() { Sum = 0; NoOfItems = 0; }

        static int GetSum() { return Sum; }

        //Get Sum for the series
        public static int SumSeriesElement(int N)
        {
            //Reset global variables
            SumSeries.Reset();

            //1). Create instances for N items using Linq
            new SumSeries[N].ToList().ForEach(c => c = new SumSeries());
            //OR
            //2). Create instances for N items using recursion
            //SumSeries.CreateInstancesRecursively(N);
            return SumSeries.GetSum();            
        }


        //Using recursion create N instance to calculate sum
        static int CreateInstancesRecursively(int N)
        {
            if (N == 0)
                return SumSeries.GetSum();
            else
            {
                var temp = new SumSeries();
                return CreateInstancesRecursively(N - 1);
            }
        }

    }
}