CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2007
    Posts
    77

    having trouble writing a recursive algorithm for 2^n

    i am writing a recursive algorithm for the function 2^n, and the formula that must be used is: 2^(n-1) + 2^(n-1) = 2^n
    heres what i have so far:
    Code:
    //computes 2^n recursively using the formula 2^n=2^n-1 + 2^n-1
    x(int n)
    {
         if(n=0)
              return 1;
         else
    }
    i am not sure how to do the recursion to get that formula, can someone point me in the right direction? thanks

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: having trouble writing a recursive algorithm for 2^n

    Do you understand the concept of recursion? Your statement should include at least one call to the x() function.

  3. #3
    Join Date
    Aug 2005
    Location
    LI, NY
    Posts
    576

    Re: having trouble writing a recursive algorithm for 2^n

    Quote Originally Posted by kevinskrazyklub View Post
    i am writing a recursive algorithm for the function 2^n, and the formula that must be used is: 2^(n-1) + 2^(n-1) = 2^n
    heres what i have so far:
    Code:
    //computes 2^n recursively using the formula 2^n=2^n-1 + 2^n-1
    x(int n)
    {
         if(n=0)
              return 1;
         else
    }
    i am not sure how to do the recursion to get that formula, can someone point me in the right direction? thanks
    Just think about it algebraically:

    2^n = 2^(n-1) + 2^(n-1) = 2 * 2^(n-1)
    x(n) = 2^n
    x(n) = 2 * x(n-1)

    Make sense? I haven't written any code and I still feel like I'm giving away the answer.
    - Alon

  4. #4
    Join Date
    Jul 2007
    Posts
    77

    Re: having trouble writing a recursive algorithm for 2^n

    Quote Originally Posted by Hermit View Post
    Just think about it algebraically:

    2^n = 2^(n-1) + 2^(n-1) = 2 * 2^(n-1)
    x(n) = 2^n
    x(n) = 2 * x(n-1)

    Make sense? I haven't written any code and I still feel like I'm giving away the answer.
    makes perfect sense thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured