/* 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 ?

Recommended Answers

All 3 Replies

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.

LONG_MAX is a constant found in <limits.h>/<climits>.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.