Home » Software » Language » Java Programming » Java program – Harmonic numbers

Java program – Harmonic numbers



public class Harmonic { 
    public static void main(String[] args) { 

        // command-line argument
        int N = Integer.parseInt(args[0]);

        // compute 1/1 + 1/2 + 1/3 + ... + 1/N
        double sum = 0.0;
        for (int i = 1; i <= N; i++) {
            sum += 1.0 / i;
        }

        // print out Nth harmonic number
        System.out.println(sum);
    }

}


/*************************************************************************
 *  Execution:    java Harmonic N
 *  
 *  Prints the Nth harmonic number: 1/1 + 1/2 + ... + 1/N.
 * 
 *  % java Harmonic 10
 *  2.9289682539682538
 *
 *  % java Harmonic 10000
 *  9.787606036044348
 *
 *************************************************************************/



Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *

Scroll To Top