/*
 * psqrt - calculate square roots modulo a prime
 *
 * Copyright (C) 1999  David I. Bell
 *
 * Calc is open software; you can redistribute it and/or modify it under
 * the terms of the version 2.1 of the GNU Lesser General Public License
 * as published by the Free Software Foundation.
 *
 * Calc is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU Lesser General
 * Public License for more details.
 *
 * A copy of version 2.1 of the GNU Lesser General Public License is
 * distributed with calc under the filename COPYING-LGPL.  You should have
 * received a copy with calc; if not, write to Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * @(#) $Revision: 30.1 $
 * @(#) $Id: psqrt.cal,v 30.1 2007/03/16 11:09:54 chongo Exp $
 * @(#) $Source: /usr/local/src/bin/calc/cal/RCS/psqrt.cal,v $
 *
 * Under source code control:	1990/02/15 01:50:35
 * File existed as early as:	before 1990
 *
 * Share and enjoy!  :-)	http://www.isthe.com/chongo/tech/comp/calc/
 */

/*
 * Returns null if number is not prime or if there is no square root.
 * The smaller square root is always returned.
 */


define psqrt(u, p)
{
	local	p1, q, n, y, r, v, w, t, k;

	p1 = p - 1;
	r = lowbit(p1);
	q = p >> r;
	t = 1 << (r - 1);
	for (n = 2; ; n++) {
		if (ptest(n, 1) == 0)
			continue;
		y = pmod(n, q, p);
		k = pmod(y, t, p);
		if (k == 1)
			continue;
		if (k != p1)
			return;
		break;
	}
	t = pmod(u, (q - 1) / 2, p);
	v = (t * u) % p;
	w = (t^2 * u) % p;
	while (w != 1) {
		k = 0;
		t = w;
		do {
			k++;
			t = t^2 % p;
		} while (t != 1);
		if (k == r)
			return;
		t = pmod(y, 1 << (r - k - 1), p);
		y = t^2 % p;
		v = (v * t) % p;
		w = (w * y) % p;
		r = k;
	}
	return min(v, p - v);
}
