Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Sum {
- // Java program to find and print the sum of the series on the next line below.
- // 1 + (1/2) - (1/3) + (1/4) - (1/5) ...
- /**
- * Method prints the sum of the given series using recursive computation
- * and calling itself at the return statement. A special case is
- * considered when N == 1, and it should throw an exception for N < 1.
- *
- * @param n - is the number of terms. Higher values for this variable
- * correspond to increased accuracy for the sum of this series.
- * @return calls "fancySumRecursive" to in fact be recursive.
- */
- public static double fancySumRecursive(long n) {
- if (n < 1) {
- throw new IllegalArgumentException("Number of terms must"
- + "be greater than 0");
- } else if (n == 1) {
- return 1.0;
- }
- return 1.0 / n + fancySumRecursive(n - 1);
- }
- // Driver code
- public static void main(String[] args) {
- int n = 100;
- // I set the print to 100 places after the decimal to observe where
- // the precision of this method can compute the sum.
- System.out.printf("%.100f", fancySumRecursive(n-1));
- }
- }
- // This recursive method computes the sum to be the value below.
- // 5.17737751763962100000000000000000000000000000000000000000000000000000
- // My old non-recursive version of this program gave me the value below.
- // 5.18737751763962100000000000000000000000000000000000000000000000000000
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement