/* For all the functions below, return TRUE if the
   calculation is successful, FALSE if overflow occurs
   Return the calculated value in the pass by reference
   parameter provided
*/

Boolean calcFactorial (int n, int* nfact)
{
	unsigned long int count = 1;
	unsigned long int result = 1;

	while(count <= n)
	{
		if(*nfact <= 0)  // not sure about this.
		{
			return FALSE;
		}
		else
		{
			result = result * count;

			count++;
		}
	}
	return TRUE;
}

Factorial is: n! = n * (n-1) * (n-2) * . . . * 3 * 2 * 1
Can someone please check if my coding is correct, especially the "if(*nfact <= 0)" which is checking for overflow ?

I might choose this for overflow checking.

if ( *nfact > INT_MAX / count )

I've also discarded result and used *nfact in its place.

/* For all the functions below, return TRUE if the
   calculation is successful, FALSE if overflow occurs
   Return the calculated value in the pass by reference
   parameter provided
*/

Boolean calcFactorial (int n, int* nfact)
{
	long count = 1;
	long max;

	while(n > 0)
	{
		if(*nfact > max / count)
		{
			return FALSE; 
		}
                else
		{
			*nfact = *nfact * count;

			n++;
		}
	}
	return TRUE;
}

How's this so far? I cannot test this yet because this is just part of a larger program. So, i have to make sure this function is correct.

This article has been dead for over six months. Start a new discussion instead.