Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Sum of Powers using recursion

  1. #1
    Junior Member
    Join Date
    Sep 2014
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Sum of Powers using recursion

    i got a little bit of problem with my coding for finding the total sum..

    the formula given to me is 1^k+2^k+...+n^k.
    my coding as follows:
      public int sumPowTo (int n, int k)
      {
     
         if ( k == 0)
        {
          return 1;
        }
        else if ( k == 1)
        {
          return n;
        }
     
        else 
        {
          return  (n * sumPowTo(n,--k)) + (sumPowTo(n--,--k)) ;
        }
      }
    it just doesnt add up to the right amout.

    for example int sumPowTo(4,2) = 30
    but i get 28


  2. #2
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Sum of Powers using recursion

    Do not use the "--" operator when calling methods like that. The results will not be what you expect.
    Instead you should just use "n - 1" or "k - 1". The problem with the "--" operator is that it matters whether you write it infront of a variable or behind the variable and for beginner this can be extremely confusing.

    If your calculation does not return the right value, do your algorithm by hand on a piece of paper. Do it just the same way your computer would do it, perhaps you will find your mistake.

  3. #3
    Junior Member
    Join Date
    Sep 2014
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Sum of Powers using recursion

    i did try using n-1 and k-1 but the outcome still the same. i trace my program on the paper before i wrote the program the outcome is 30..

  4. #4
    Junior Member
    Join Date
    Dec 2013
    Location
    London
    Posts
    11
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: Sum of Powers using recursion

    Quote Originally Posted by Red View Post
    i got a little bit of problem with my coding for finding the total sum..

    the formula given to me is 1^k+2^k+...+n^k.
    my coding as follows:
      public int sumPowTo (int n, int k)
      {
     
         if ( k == 0)
        {
          return 1;
        }
        else if ( k == 1)
        {
          return n;
        }
     
        else 
        {
          return  (n * sumPowTo(n,--k)) + (sumPowTo(n--,--k)) ;
        }
      }
    it just doesnt add up to the right amout.

    for example int sumPowTo(4,2) = 30
    but i get 28
    Can you please explain, why do you expect your code to have 30? Also, I checked this recursive method in java and it gives a result of 17, which is quite understandable if carefully counting code:

    #1 n=4 and k=2, therefore first two conditions are taken off, and third else applies which is recursive
    #2 as n=4 - it stays in first bracket and as --k is 1 now recursive method returns n - which is 4 again; altogether first brackets is given result of 16
    #3 second bracket recursive, but values sent to it are 4 (as n still to be 4) and 0 (as k was after --k - 1 and another --k becomes 0)

    Therefore I can't understand why do you get 28, and why do you expect it to be 30?

  5. The Following User Says Thank You to skuch89 For This Useful Post:

    Red (September 17th, 2014)

  6. #5
    Junior Member
    Join Date
    Sep 2014
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Sum of Powers using recursion

    Quote Originally Posted by skuch89 View Post
    Can you please explain, why do you expect your code to have 30? Also, I checked this recursive method in java and it gives a result of 17, which is quite understandable if carefully counting code:

    #1 n=4 and k=2, therefore first two conditions are taken off, and third else applies which is recursive
    #2 as n=4 - it stays in first bracket and as --k is 1 now recursive method returns n - which is 4 again; altogether first brackets is given result of 16
    #3 second bracket recursive, but values sent to it are 4 (as n still to be 4) and 0 (as k was after --k - 1 and another --k becomes 0)

    Therefore I can't understand why do you get 28, and why do you expect it to be 30?

    from the tracing that i have made is 1^2+2^2+3^2+4^2 = 30 [int (4,2)}
    or in other example 1^3+2^3+3^3+4^3+5^3 = 225 [int (5,3)]

    that i need help in detecting the hole in my program and the reason why i cant get 30 as the answer.

  7. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Sum of Powers using recursion

    In future posts:

    1. Post code that can be run,
    2. Comment your code to describe what is (or should be) happening, and
    3. Post sample runs that show or instructions to duplicate the undesired behavior.

    I suggest adding some debug code to reveal what your recursive method is doing. For example, you might add a first line to the method like:

    System.out.printf( "In sumPowTo() with n = %d and k = %d.\n", n, k );

    You might also ask yourself how n^k is being calculated and included as a term of the series.

  8. #7
    Junior Member
    Join Date
    Dec 2013
    Location
    London
    Posts
    11
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: Sum of Powers using recursion

    Quote Originally Posted by Red View Post
    from the tracing that i have made is 1^2+2^2+3^2+4^2 = 30 [int (4,2)}
    or in other example 1^3+2^3+3^3+4^3+5^3 = 225 [int (5,3)]

    that i need help in detecting the hole in my program and the reason why i cant get 30 as the answer.
    Well, then your logic with recursive method is incorrect, think of this: you have a number 4 and 2 which are sent as parameters. Every time recursion happens first number (which is four) is changing. You started from 1^2, I suggest try to start from 4 instead and every time recursion happens go for -1, so next will be 3, then 2 and so on. Also if n (variable) reaches 0 - is return only from recursion, or if you decide go for 1 then return only k option. Hope this will give you some ideas how to work out algorithm

  9. The Following User Says Thank You to skuch89 For This Useful Post:

    Red (September 17th, 2014)

  10. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Sum of Powers using recursion

    @Red: Any progress?

    In addition to the above suggestions, I noted that your assumptions for k == 0 and k == 1 are incorrect. Think about what happens for those cases. Pick small values for n and k and work through the solutions by hand for both cases. And then if those assumptions are wrong, what should the real base case be? A good starting point for defining the base case is to include the variable that is changed with each pass.

  11. The Following User Says Thank You to GregBrannon For This Useful Post:

    Red (September 17th, 2014)

  12. #9
    Junior Member
    Join Date
    Sep 2014
    Posts
    4
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Sum of Powers using recursion

    Quote Originally Posted by GregBrannon View Post
    @Red: Any progress?

    In addition to the above suggestions, I noted that your assumptions for k == 0 and k == 1 are incorrect. Think about what happens for those cases. Pick small values for n and k and work through the solutions by hand for both cases. And then if those assumptions are wrong, what should the real base case be? A good starting point for defining the base case is to include the variable that is changed with each pass.
    yeap got it solved...

    public int sumPowTo (int n, int k)
     // Method for calculating sum of powers, which using the power method above
      {
         if ( n == 0) // Base case, if n equals to 0 the outcome will be 0
        {
          return 0;
        }
        else 
        {
          int pow = (n* pow(n,k-1)); 
    // Defining the power that being called from the above method
          return  pow + (sumPowTo(n-1,k)) ;
        }
      }

    made a mistake in declaring the base case.

    now time for me to get back on the chess.. fyi this code is suppose to be not to run like other code it can only interact with the dev.. i was asked to not used any static or any system.out...
    Last edited by Red; September 17th, 2014 at 06:19 AM.

  13. #10

    Default Re: Sum of Powers using recursion

    import java.io.*;
    class Power
    {
    public static void main(String args[]) throws IOException
    {
    BufferedReader br = new BufferedReader(new
    InputStreamReader(System.in));
    Power call = new Power();
    System.out.print("Enter number : ");
    int x = Integer.parseInt(br.readLine());
    System.out.print("Enter power : ");
    int y = Integer.parseInt(br.readLine());
    System.out.println("\n" +x +"^" +y +" = "+call.findPower(x,y));
    }
    int findPower(int x, int y)
    {
    if(y==0)
    return 1;
    else if(y==1)
    return x;
    else
    return x*findPower(x,y-1);
    }
    }

Similar Threads

  1. Sum from a file
    By mikerousse in forum What's Wrong With My Code?
    Replies: 1
    Last Post: January 4th, 2014, 05:04 PM
  2. sum of digits
    By snarayana.murthy86 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 18th, 2013, 02:40 PM
  3. Quick Recursion question involving sum
    By ManInTheMiddle in forum Algorithms & Recursion
    Replies: 6
    Last Post: December 1st, 2012, 08:19 AM
  4. Fibonacci with matrixes and recursive powers
    By Enrico123 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 28th, 2010, 08:51 AM
  5. Program to compute powers
    By Shyamz1 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: October 25th, 2010, 04:51 PM