• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Untitled

a guest Apr 26th, 2019 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. public class Sum {
2. // Java program to find and print the sum of the series on the next line below.
3. //    1 + (1/2) - (1/3) + (1/4) - (1/5) ...
4.     /**
5.      * Method prints the sum of the given series using recursive computation
6.      * and calling itself at the return statement. A special case is
7.      * considered when N == 1, and it should throw an exception for N < 1.
8.      *
9.      * @param n - is the number of terms. Higher values for this variable
10.      *          correspond to increased accuracy for the sum of this series.
11.      * @return calls "fancySumRecursive" to in fact be recursive.
12.      */
13.     public static double fancySumRecursive(long n) {
14.         if (n < 1) {
15.             throw new IllegalArgumentException("Number of terms must"
16.                     + "be greater than 0");
17.         } else if (n == 1) {
18.             return 1.0;
19.         }
20.         return 1.0 / n + fancySumRecursive(n - 1);
21.     }
22.     // Driver code
23.     public static void main(String[] args) {
24.         int n = 100;
25.         // I set the print to 100 places after the decimal to observe where
26.         // the precision of this method can compute the sum.
27.         System.out.printf("%.100f", fancySumRecursive(n-1));
28.     }
29. }
30. // This recursive method computes the sum to be the value below.
31. // 5.17737751763962100000000000000000000000000000000000000000000000000000
32. // My old non-recursive version of this program gave me the value below.
33. // 5.18737751763962100000000000000000000000000000000000000000000000000000
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top