write a program in Java that will find sum of factorials of all the prime numbers with alternating signs within the range 1-n...n = input....
For example- n=10
2! - 3! + 5! - 7!
Answers
Answer:
public class Fact
{
public static void main(String[] args)
{
int cf=0,c=0,of=1,ef=1,sum=0;
for(int i=2;i<=10;i++)
{
for(int j=2;j<=i;j++)
{
if(i%j==0)
{
cf++; //to find the prime
}
}
if(cf==1) // check the prime condition whether factor is equal to 1 or not.
{
c++; // to increase a count, later we use it for + and - , by even and odd method
if(c%2!=0) // if condition is odd then + else - .This if() will check that.
{
for(int k=1;k<=i;k++) //odd +
of=of*k; //to find the factorial of odd counter i.e., 2! 5! so on
sum=sum+of;
}
else
{
for(int l=1;l<=i;l++) //even -
ef=ef*l; //to find the factorial of even counter i.e., 3! 7! so on..
sum=sum-ef;
}
}
of=1; //again 0 , to calculate new factorial value
ef=1;
cf=0; //for prime
}
System.out.println(sum);
}
}
Explanation: