# Thread: Sum of fractions with factorial function. need help.

1. ## Sum of fractions with factorial function. need help.

I am trying to write a program which will solve the following expression:

(1/2)-(1/2^2!)+(1/2^3!)-(1/2^4!)+(1/2^5!).......+-(1/2^(n-1)!)+-(1/2^n!)

I have been trying to debug it for a couple of hours now and I can't understand what is wrong. I have tested it with n=5 which should return ~0.26562494 and it is returing 136.

Here's what I have:
Code:
```#include <stdio.h>

long int factor(int num1){
int x;
long int fact;
fact = 1;
for ( x=1; x <= num1; x++ ){
fact = fact*x;
}
return (fact);
}

float main(){
int pt, sign, n;
float frac, som;
pt = 1;
sign = -1;
som = 0;
scanf("%d", &n);
for (pt = 1; pt <= n; pt++){
sign = sign * -1;
frac = sign * ( 1 / ( 2 ^ factor(pt) ) );
som = som + frac;
}
return(som);
}```
If you happen to find outwhat is wrong, please do share it. If you notice something that could be done in a better way but doesn't have to do with this problem in particular, please share it aswell.

Tiago Figueiró

2. You are using integer math, so any fraction is dropped. Example 1/2 would be 0.

Code:
`2 ^ factor(pt) )`
The caret is the XOR operator, not the power.

Also main must be defined to return an int, not a float.

Jim

3. Thank you for your help.

So what is the power operator? And what do you mean by "integer" math, since I have defined frac to be a float?

Please understand I have just started programming and there are some concepts I am not accustomed to.

thanks

4. There is no power operator. You either do the multiplication or call the pow()

In the following formula you have used integer math:
Code:
`frac = sign * ( 1 / ( 2 ^ factor(pt) ) );`
Because all the values to the right of the equal sign are integers integer math will be preformed. In order to force floating point math you will need to in sure that each section of the equation has at least one floating point number. I would suggest unless absolutely necessary, that you do not mix floating point math with integer math. So to fix the above equation use:
Code:
```float point = factor(pt);
frac = (float)sign * ( 1.0 /(point * point));```
Jim

5. Yaiks!

Working program:
Code:
```#include <stdio.h>
#include <math.h>

long int factor(int num1){
int x;
long int fact;
fact = 1;
for ( x=1; x <= num1; x++ ){
fact = fact*x;
}
return (fact);
}

int main(){
int pt, sign, n;
float frac, som;
pt = 1;
sign = -1.0;
som = 0.0;

scanf("%d", &n);
for (pt = 1; pt <= n; pt++){
sign = sign * -1.0;
float point = factor(pt);
frac = (float)sign * ( 1.0 / pow(2, point) );
som = som + frac;
}
printf("%f", som);
return(0);
}```
Thumbs up for you