Understanding how recursive functions work

后端 未结 18 775
野性不改
野性不改 2020-11-22 07:08

As the title explains I have a very fundamental programming question which I have just not been able to grok yet. Filtering out all of the (extremely clever) \"In order to

18条回答
  •  终归单人心
    2020-11-22 07:38

    I'll give it a go.

    Executing the equation a + sumInts(a+1, b), I will show how the final answer is 14.

    //the sumInts function definition
    func sumInts(a: Int, b: Int) -> Int {
        if (a > b) {
            return 0
        } else {
            return a + sumInts(a + 1, b)
        }
    }
    
    Given: a = 2 and b = 5
    
    1) 2 + sumInts(2+1, 5)
    
    2) sumInts(3, 5) = 12
       i) 3 + sumInts(3+1, 5)
       ii) 4 + sumInts(4+1, 5)
       iii) 5 + sumInts(5+1, 5)
       iv) return 0
       v) return 5 + 0
       vi) return 4 + 5
       vii) return 3 + 9
    
    3) 2 + 12 = 14.
    

    Let us know if you have any further questions.

    Here's another example of recursive functions in the following example.

    A man has just graduated college.

    t is the amount of time in years.

    The total actual number of years worked before retiring, can be calculated as follows:

    public class DoIReallyWantToKnow 
    {
        public int howLongDoIHaveToWork(int currentAge)
        {
          const int DESIRED_RETIREMENT_AGE = 65;
          double collectedMoney = 0.00; //remember, you just graduated college
          double neededMoneyToRetire = 1000000.00
    
          t = 0;
          return work(t+1);
        }
    
        public int work(int time)
        {
          collectedMoney = getCollectedMoney();
    
          if(currentAge >= DESIRED_RETIREMENT_AGE 
              && collectedMoney == neededMoneyToRetire
          {
            return time;
          }
    
          return work(time + 1);
        }
    }
    

    And that should be just enough to depress anyone, lol. ;-P

提交回复
热议问题