non-built-in exponentiation (Re: What should be added to C)

Doug Gwyn gwyn at brl-smoke.ARPA
Mon Jun 16 16:06:21 AEST 1986


/*
	LPow -- long exponentiation (no overflow detection)

	last edit:	86/06/16	D A Gwyn

	SCCS ID:	@(#)lpow.c	1.1
*/

long
LPow( base, exponent )			/* returns base^exponent */
	register long	base;
	register long	exponent;
	{
	register long	result;		/* result accumulator */

	/* handle simple special cases separately: */

	if ( base == 0 )
		return 0;		/* exp. < 0 should be EDOM */
	else if ( base == 1 )
		return 1;
	else if ( base == -1 )
		return exponent % 2 == 0 ? 1 : -1;
	else if ( exponent < 0 )
		return 0;

	/* general case with exponent >= 0: */

	result = 1;

	for ( ; ; )	/* LOOP INVARIANT: result*base^exponent */
		{
		if ( exponent % 2 != 0 )
			result *= base;

		if ( (exponent /= 2) == 0 )
			break;		/* result now stable */

		base *= base;
		}

	return result;
	}



More information about the Comp.lang.c mailing list