# Thread: alternating series sum java help

1. Member
Join Date
Mar 2011
Posts
27
Rep Power
0

## alternating series sum java help

For my assignment I have to create a program that calculates the following:

x - x^3/3! + x^5/5! - x^7/7! + ..... + - x^n/n!

Where the user inputs the value of x they want to calculate and inputs the value of n for the maximum exponent value (the higher the exponent the user inputs the more accurate the calculation will be).

Here's my attempt to the problem:

Java Code:
```import java.io.*;
public class s {
public static void main(String args[]) throws IOException
{

double x;
int n;

System.out.print("Input a value for x: ");

System.out.print("Input max exponent: ");

int factorial=1;
for (int i=2; i<=n; i++)                // this for loop finds factorials (ie 5!=120)
{
factorial = factorial * i;
}

int exp=1;
double sum = 0;
for (int i=1; i<=n; i=i+2)
{
sum = sum + (Math.pow(-1,i))*(Math.pow(x,i))/(factorial);
// i don't think I did the factorial part correctly.
// Also I can't get the alternating between positive and negative. it starts with negative because (-1)^1= -1 but the first term of series has to be positive.
}

System.out.println("The result is: " + sum);
}

}```
Last edited by java157; 03-19-2011 at 12:24 AM.

2. This wont really work easily without a static method to fomput the factorial.

You can more easily break each expression down to
Java Code:
`x^((2n + 1)/((2n + 1)!)`
so you would want to do something like
Java Code:
`Math.pow(x, ((2n + 1)/yourFactorialMethod(2n + 1)));`
I gave you a decent amount here, but I left you with figuring a bit out, create a static factorial class and post the code for it.(start small, work up)

3. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
15
Does your code compile? If not and you can't understand the messages post them.

If it runs but the runtime behaviour is not what you expect (ie it gives a strange answer or throws an exception), say what it does.

And please use code tags: put [code] at the start of your code and [/code] at the end: that way the indentation is preserved.

-----

// i don't think I did the factorial part correctly.

One way to see to to print out the value produced by your factorial loop.

Java Code:
```int factorial=1;
for (int i=2; i<=n; i++) // this for loop finds factorials (ie 5!=120)
{
factorial = factorial * i;
}
[color=blue]System.out.println("n=" + n);
System.out.println("n!=" + factorial);[/color]```

4. Member
Join Date
Mar 2011
Posts
27
Rep Power
0
Originally Posted by pbrockway2
Does your code compile? If not and you can't understand the messages post them.
code compiles, but does not output correct answer

5. Member
Join Date
Mar 2011
Posts
27
Rep Power
0
Is it possible to create a for loop within a for loop? Would that work?

6. Best way to find out is to try it and see for yourself!

db

7. By the way, @op, were you able to do the last problem?
E(2n + 1)!

If you were this is sort of just a step up from that as I pointed out above.

8. Member
Join Date
Mar 2011
Posts
27
Rep Power
0
Originally Posted by sunde887
I gave you a decent amount here, but I left you with figuring a bit out, create a static factorial class and post the code for it.(start small, work up)
Is it possible to do this without creating a new class?

9. yes. One class can have many methods, I am wanting you to have one of the methods in the class be a factorial method. Below I have created a static method to print hello.

Java Code:
```public class StaticHello{
public static void hello(){
System.out.println("Hello, World");
}
public static void main(String[] args){
hello();
}
}```

10. Member
Join Date
Mar 2011
Posts
27
Rep Power
0
Originally Posted by sunde887
yes. One class can have many methods, I am wanting you to have one of the methods in the class be a factorial method. Below I have created a static method to print hello.

Java Code:
```public class StaticHello{
public static void hello(){
System.out.println("Hello, World");
}
public static void main(String[] args){
hello();
}
}```
Ok I think I get it now, but under the factorial method it says "the local variable n may not have initialized". Says something similar for FactorialMethod (check comments within the code):

Java Code:
```import java.io.*;
public class s{
public static void main(String args[]) throws IOException
{

double x;
int n;

System.out.print("Input a value for x: ");

System.out.print("Input max exponent: ");

double sum;
for (int i=0; i<=n; i++)
{
sum += (Math.pow(-1,i))*(Math.pow(x,((2*n + 1))/((2*n + 1)FactorialMethod); // "FactorialMethod cannot be resolved to a variable"
}
System.out.println("The result is: " + sum);
}

public static int FactorialMethod;{
int n;
int factorial=1;
for (int i=2; i<=n; i++) //"the local variable n may not have initialized"
{
factorial *= i;
}
}

}```

11. close, to help you out a bit more I will make a static method to determine if a number is prime.

Java Code:
```public class IsPrime{
public static boolean isPrime(int n){
boolean flag = true; //assume the number is prime
for(int i = 2; i < n; i++){
if(n % i == 0){//if number is evenly divisble by i, switch flag to false, end loop.
flag = false;
break;
}
}
return flag;//return the flag(true if nothing divides evenly into n, otherwise returns false)
}
public static void main(String[] args){
System.out.println(isPrime(10));
System.out.println(isPrime(11));
}
}```

12. Member
Join Date
Mar 2011
Posts
27
Rep Power
0
Originally Posted by sunde887
close, to help you out a bit more I will make a static method to determine if a number is prime.

Java Code:
```public class IsPrime{
public static boolean isPrime(int n){
boolean flag = true; //assume the number is prime
for(int i = 2; i < n; i++){
if(n % i == 0){//if number is evenly divisble by i, switch flag to false, end loop.
flag = false;
break;
}
}
return flag;//return the flag(true if nothing divides evenly into n, otherwise returns false)
}
public static void main(String[] args){
System.out.println(isPrime(10));
System.out.println(isPrime(11));
}
}```
It still says n can't be initialized to a variable:

Java Code:
```public static int FactorialMethod;{
int n;
boolean flag = true;
int factorial=1;
for (int i=2; i<=n; i++) // "n has not been initialized to variable"
{
if ((n % i == 0)){
flag = false;
break;
}
else
{
factorial *= i;
}
}

}
}```
How to I make the n equal to the value that the user inputs into the main method (or whatever it's called :D)

13. Your method is incorrect(you don't need a flag to find the factorial)

The reason I used the flag was to show you a bit more complex example of a static method(one that takes an argument)

Compare my method declaration and yours

Mine:
Java Code:
`public static boolean isPrime(int n)`
yours:
Java Code:
`public static int FactorialMethod;`
Besides the name and return type there is one major difference. Where does my static method to determine if a number is prime declare n?

14. Member
Join Date
Mar 2011
Posts
27
Rep Power
0
Originally Posted by sunde887
Your method is incorrect(you don't need a flag to find the factorial)

The reason I used the flag was to show you a bit more complex example of a static method(one that takes an argument)

Compare my method declaration and yours

Mine:
Java Code:
`public static boolean isPrime(int n)`
yours:
Java Code:
`public static int FactorialMethod;`
Besides the name and return type there is one major difference. Where does my static method to determine if a number is prime declare n?
Here it says "Syntax error on 'FactorialMethod', delete this token"

Java Code:
`sum += (Math.pow(-1,i))*(Math.pow(x,2*n + 1))/((2*n + 1)FactorialMethod);`
Also have another error below
Here it says. "This method must return a result of type boolean"

Java Code:
` public static boolean FactorialMethod(int n){`
Last edited by java157; 03-19-2011 at 02:24 AM.

15. Ill give you the factorial method since you seem to be genuinely trying but I want you to understand how it works, instead of simply copying and pasting it.

Java Code:
```public static int factorial(int n){  //it's public and static, it returns and int, and takes an int as an argument
for(int i = n; i > 0; i--){
sum *= i;
}
}```
I left two bugs in the code which will make it not compile, you have to find them(this forces you to think about it instead of copy/pasting).

Once you find the bugs you want to work on the actual heart of the problem.

Which really breaks down to
Math.pow(x, ((2n + 1)/(factorial(2n + 1))));

16. Member
Join Date
Mar 2011
Posts
27
Rep Power
0
Originally Posted by sunde887
Ill give you the factorial method since you seem to be genuinely trying but I want you to understand how it works, instead of simply copying and pasting it.

Java Code:
```public static int factorial(int n){  //it's public and static, it returns and int, and takes an int as an argument
for(int i = n; i > 0; i--){
sum *= i;
}
}```
I left two bugs in the code which will make it not compile, you have to find them(this forces you to think about it instead of copy/pasting).

Once you find the bugs you want to work on the actual heart of the problem.

Which really breaks down to
Math.pow(x, ((2n + 1)/(factorial(2n + 1))));
It took me several hours (looking through tutorials and figuring it out) to get this done. I'm glad you helped me instead of just giving me the answer because I actually learned something. Thank you :)

17. Did you get the whole problem solved?

18. Member
Join Date
Mar 2011
Posts
27
Rep Power
0
Yes. The program works fine and calculates correct answers