/*
 *
 * Copyright 1998-1999, University of Notre Dame.
 * Authors: Jeffrey M. Squyres, Kinis L. Meyer with M. D. McNally 
 *          and Andrew Lumsdaine
 *
 * This file is part of the Notre Dame LAM implementation of MPI.
 *
 * You should have received a copy of the License Agreement for the
 * Notre Dame LAM implementation of MPI along with the software; see
 * the file LICENSE.  If not, contact Office of Research, University
 * of Notre Dame, Notre Dame, IN 46556.
 *
 * Permission to modify the code and to distribute modified code is
 * granted, provided the text of this NOTICE is retained, a notice that
 * the code was modified is included with the above COPYRIGHT NOTICE and
 * with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE
 * file is distributed with the modified code.
 *
 * LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
 * By way of example, but not limitation, Licensor MAKES NO
 * REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
 * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
 * OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
 * OR OTHER RIGHTS.  
 *
 * Additional copyrights may follow.
 *
 *
 *	Ohio Trollius
 *	Copyright 1994 The Ohio State University
 *	RBD
 *
 *	$Id: prime.c,v 6.2 1999/06/12 20:10:57 jsquyres Exp $
 *
 *	Function:	- test and generate prime numbers
 *				- is_prime(): test is number is prime
 *				- next_prime(): return the next prime number
 */

#include <portable.h>
#include <typical.h>

/*
 *	is_prime
 *
 *	Function:	- check if the number is prime
 *	Accepts:	- a positive integer
 *	Returns:	- TRUE or FALSE
 */
int
is_prime(n)

int4			n;

{
	int4		i;		/* favourite counter */
	int4		i_2;		/* i squared */

	if (n <= 0) {
		return(FALSE);
	} else if ((n == 1) || (n == 2)) {
		return(TRUE);
	} else if ((n % 2) == 0) {
		return(FALSE);
	}
/*
 * Loop through all odd number smaller than the largest divisor
 * checking if any divides evenly the given number.
 */
	else {
		for (i = 3, i_2 = 9; i_2 <= n; i += 2) {
			if ((n % i) == 0) {
				return(FALSE);
			}

			i_2 += (i + 1) << 2;
		}
	}

	return(TRUE);
}

/*
 *	next_prime
 *
 *	Function:	- get the first prime # >= the given number
 *	Accepts:	- a positive number
 *	Returns:	- a prime number or ERROR
 */
int4
next_prime(n)

int4			n;

{
	if (n < 0) {
		return((int4) ERROR);
	} else if (n < 1) {
		return((int4) 1);
	} else if (n < 2) {
		return((int4) 2);
	} else {
/*
 * Find the next prime number in the general case.
 */
		if ((n % 2) == 0) {
			n++;
		}

		while (! is_prime(n)) {
			n += 2;
		}

		return(n);
	}
}
