Using recursion to sum numbers

后端 未结 16 2112
轮回少年
轮回少年 2021-02-05 15:45

I have just been studying the concept of recursion and I thought that I would try a simple example. In the following code, I am attempting to take the numbers: 1, 2, 3, 4, 5, an

16条回答
  •  佛祖请我去吃肉
    2021-02-05 16:21

    To begin at the end, a recursive Sum method looks like this:

        // version 3
    
        public static int Sum(int startRange, int endRange)
        {
            if (endRange > startRange)
            {
                return endRange + Sum(startRange, endRange - 1);
    
            }
    
            if (endRange < startRange)
            {
                return startRange + Sum(endRange, startRange - 1);
    
            }
    
            return endRange; 
    
        }
    

    Hardcoding the startRange to be 0 gives us:

        // version 2
    
        public static int Sum(int range)
        {
            if (range > 0)
            {
                return range + Sum(0, range - 1);
    
            }
    
            if (range < 0)
            {
                return Sum(range, -1);
    
            }
    
            return range;
    
        }
    

    ...and if you want to limit the method to positive numbers only, there's no need for a sign:

        // version 1
    
        public static unsigned int Sum(unsigned int range)
        {
            if (range > 0)
            {
                return range + Sum(0, range - 1);
    
            }
    
            return range;
    
        }
    

    I hope this helps give more of an insight into summing number ranges via recursion.

提交回复
热议问题