I want to find the sum using basic loops, so I used the following code:
// sum of first n terms in the series, 1 - 1/1! + 2/2! - 3/3!...
package assignment02;
import java.util.Scanner;
public class P7Bnew {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter number of terms.");
int n = in.nextInt();
// using for loop to find sum
double sum =1;
for (int i =1; i<n ; i++)
{
int fact = 1;
for (int j=1; j<=i; j++)
{
fact *= i;
}
if (i%2==0)
sum+= ((int)i/fact);
else
sum -= ((int)i/fact);
}
System.out.println("The sum of first "+n+ " terms is "+sum);
}
}
I want to restrict from using the predefined functions. In this way I am getting sum as 1 for n>=4. So I tried another way for alternately adding and subtracting terms from :
import java.util.*;
import java.lang.*;
import java.io.*;
class P7B
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner (System.in);
int a = in.nextInt();
double sum = 1;
for (int i=1; i<a ; i++)
{
int fact=1;
for (int j=2; j<=i;j++)
{
fact = fact * j;
}
int sign;
if ((i%2)==0)
sign =1;
else
sign = -1;
sum = (sum + (sign*(i/fact)));
}
System.out.println("The sum of the first "+a+ " terms of the series 1 - (1/1!) + (2/2!) - (3/3!)... is "+(sum)+".");
}
}
But I got same results. Later when I used Math.pow(-1, i) instead of the sign variable, it gave me the correct result. Please tell me the reason my initial attempts were giving incorrect sum for n>=4.