Write a java program to find out the sum of harmonic series :
1 + ½ + 1/3 + ……… up to nth term , for any value of n.

Answers were Sorted based on User's Feedback



Write a java program to find out the sum of harmonic series : 1 + ½ + 1/3 + ……… up to ..

Answer / sourav dey

import java.io.*;
class Hermonic{
public static void main(String args[]){
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
double result = 0.0;
int num=0;
try{
System.out.println("Enter a term which you want to sum:");
num = Integer.parseInt(in.readLine());
}
catch(Exception e){}
while(num > 0){
result = result +( (double) 1 / num);
num--;
}
System.out.println("Output of Harmonic Series is "+result);
}
}

Is This Answer Correct ?    12 Yes 0 No

Write a java program to find out the sum of harmonic series : 1 + ½ + 1/3 + ……… up to ..

Answer / s

package com.adder;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class GeneralJava {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println(new GeneralJava().process
(10));
}

private double process(int n) {

BigDecimal retVal = BigDecimal.ZERO;

for (int i=1; i<= n; i++) {

BigDecimal adder =
BigDecimal.ONE.divide(BigDecimal.valueOf(i),10,
RoundingMode.HALF_UP);

retVal = retVal.add(adder);

}

return retVal.doubleValue();
}
}

Is This Answer Correct ?    4 Yes 4 No

Post New Answer

More Advanced Java Interview Questions

What is Servlet Filter And What does it work?

1 Answers   TCS,


What are the different approaches to represent an inheritance hierarchy?

0 Answers  


Difference between loadclass and class.forname?

0 Answers  


When a thread blocks on i/o, what state does it enter?

0 Answers  


Define prototype?

0 Answers  






How will the struts know which action class to call when you submit a form?

6 Answers   HeadStrong,


AS a developer will u create a data source in connection pool? If so how will u do that, how to access the object from connection pool using IRAD tool?

0 Answers  


can a static method be overridden

41 Answers   IBM, SolutionNET,


Different between Struts and Spring? or Why use Spring, if you are already using Struts?

3 Answers   HP,


When a thread terminates its processing, it enters into what state?

1 Answers  


Have you used threads in Servelet?

0 Answers   Satyam,


What is ioc concept & explain it?

0 Answers  


Categories