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 a dirty read?

1 Answers  


How to synchronize jsp page?

1 Answers   Infotech, TCS,


Explain the methods of Naming class, rebind( ) and lookup()?

1 Answers  


Why is main purpose of XML?

5 Answers  


If we opened windows notepad 4 times, does it starts 4 processes or 4 threads?

1 Answers  


what is DGC?

1 Answers  


life cycle of an applet?

3 Answers  


What is Lock Based Protocol and what is its use?

2 Answers   Wipro,


which type of objects reference will be given to client?

0 Answers  


Explain Object Serialization and it can be used?

3 Answers   Infosys,


What is Stream Tokenizer?

0 Answers   TCS,


what is catalina in tomcat server.

11 Answers   IBM,


Categories