Why isn't it giving the factorial properly.

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>
using namespace std;

long fact(int n)
{
    if (n<0)
    return 0;
    
    int f(1);
    while (n>0, f<n)
    n *= f++;
    return n;
}

int main()
{
    int x;
    cin >> x;
    cout << fact(x);
    system ("pause");
    return 0;
}
    


However when I used this in the
 
long fact(int n) 
function, It was compiling well.
1
2
3
4
int f(1);
while (n>1)
     f *= n--;
     return f;
1) while (n>0, f<n) is equivalent to while (f<n)
2) you are multiplying n by f (making it way larger than it was before) and increment f (making it slightly larger). n increases faster than f and f will always be less than n... until n overflows, after that anything could happen.
Topic archived. No new replies allowed.