1

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.

bbahd
  • 49
  • 8
  • And please see [mcve]. Dont just give us fragments of your code, tell us about the data you are testing your code with, and what the expected/actual results are. – GhostCat Jan 05 '22 at 08:28
  • @user16320675 oops, I meant to cast `i` to `double` not to `int`. (i.e. `(double)i/fact`) – Eran Jan 05 '22 at 08:40

1 Answers1

5

Your problem is that in i/fact as well as in (sign*i)/fact all operands are ints and thus you will get 0 as the result of that calculation (1/2 etc. is 0 in integer math and so will be i/i! with the exception of 1/1!and 2/2! because that's just 1/1 and 2/2). When using Math.pow(-1,i) you get a double and now the calculation works.

So to fix your code use a cast to double:

if (i%2==0)
     sum += (double)i/fact;
else 
     sum -= (double)i/fact;
Thomas
  • 87,414
  • 12
  • 119
  • 157
  • After typecasting, the values n>=4 are now in double format but it is giving wrong value, for example, n=4 it should give 0.5 but is giving 0.6666666666666667. Please help in this. – bbahd Jan 05 '22 at 08:43
  • 1
    for n=4 it should be 4/4! = 4 / 24 = 0.16666667, seems correct to me. (i.e. 1/2 + 1/6 = 1/3) – tnavidi Jan 05 '22 at 08:48
  • So with your implementation you want to go until `3/3!` for `n = 4`? Did you debug your code to see if you're stopping at the right moment? – Thomas Jan 05 '22 at 08:52
  • @Thomas Yes, I did, it is working fine with `sum += (double)(sign*i)/fact ` , but not with ```sum += (double)i/fact``` after typecasting. – bbahd Jan 05 '22 at 08:56
  • you could change the for loop accordingly, since you want to count the first 1 as a term: `for (int i =1; i – tnavidi Jan 05 '22 at 08:57
  • @user17373135 have a look at your factorial calculation: it should be `fact *= j;` instead of `fact *= i;`. This is a case where better variable names would make it easier to spot errors like this. – Thomas Jan 05 '22 at 08:58
  • @tnavidi it is already going one term less as it working from n =1 to i – bbahd Jan 05 '22 at 09:00
  • @Thomas Oh, yes. Thank you very much. – bbahd Jan 05 '22 at 09:01