Results 1 to 5 of 5
  1. #1
    berfuzz is offline Member
    Join Date
    Feb 2011
    Posts
    43
    Rep Power
    0

    Default Harmonic sums - Recursive

    Gnarly in a recursive function!

    I can't see where I'm messing things up. Maybe it's time for a coffee break..? Anyhow, I'm trying to calculate the harmonic sum of a series.
    Java Code:
       public static double harmonicSum(int n)
       {
          double temp = 0;
          if( n == 1)
          {
             return 1;
          }
    //System.out.println("Test");    Seems to give the right number of out puts.
          temp = 1/n; 
          return temp + harmonicSum(n-1);
       }
    Please point out the faulty stuff.

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    what happens if you make the recursive line
    Java Code:
    return ((double)1 / n) + harmonicSum(n - 1);
    If that works, great, if not, what exactly is your problem?

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by sunde887 View Post
    what happens if you make the recursive line
    Java Code:
    return ((double)1 / n) + harmonicSum(n - 1);
    If that works, great, if not, what exactly is your problem?
    Why not just do this?

    Java Code:
    return 1.0 / n + harmonicSum(n - 1);
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    That works too I suppose :) (sometimes I don't enjoy thinking logically)

  5. #5
    berfuzz is offline Member
    Join Date
    Feb 2011
    Posts
    43
    Rep Power
    0

    Default

    Thanks!

    Not the first time I preform an int division. Probably not the last either...

Similar Threads

  1. recursive function
    By jayden in forum New To Java
    Replies: 11
    Last Post: 09-02-2010, 03:00 PM
  2. Problem with Sums and Averages in Sales Report
    By DavidEvans in forum New To Java
    Replies: 9
    Last Post: 04-21-2010, 08:57 PM
  3. recursive method
    By michail in forum New To Java
    Replies: 0
    Last Post: 01-31-2010, 01:50 PM
  4. basic help with Recursive
    By syntrax in forum New To Java
    Replies: 3
    Last Post: 12-15-2009, 06:19 AM
  5. Help with recursive implementation
    By toby in forum Advanced Java
    Replies: 1
    Last Post: 08-07-2007, 05:57 AM

Posting Permissions

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