[net.sources] Square root routine in C

zben@umd5.umd.edu (Ben Cranston) (04/21/87)

Sorry about this, but private mail to the advertised address bounced from
not being able to open an SMTP connection to uxc.CSO.UIUC.EDU based on:

pwcs.StPaul.GOV
	type = MX, class = IN, ttl = 172780, dlen = 20
	preference = 20, name = uxc.CSO.UIUC.EDU

and an attempt to resend to rutgers.ARPA resulted in a "user unknown" 
advisory...

> Date: Mon, 13 Apr 87 14:35:28 cst
> From: rutgers!daveg@pwcs.StPaul.GOV (Dave Glowacki)

> In article <1519@umd5.umd.edu> you write:
>> Case in point:  I just came up with a fast integer square-root routine for
>> a local project (written in C, available on request).

> I'm requesting!!!   I was just about to start writing a routine to do
> this very thing.  It'd sure save me a lot of work if you'd send me a copy.

Enjoy -zben

/* Fast integer square root test routine.
 * Ben Cranston 3/9/87
 */

int isqrt(n)
int n;
{
    int a,b,c;

    a = n;
    b = n;
    if (n>1) {
	while (a>0) {
	    a = a >> 2;
	    b = b >> 1;
	}
	do {
	    a = b;
	    c = n / b;
	    b = (c + a) >> 1;
	} while ( (a-c)<-1 || (a-c)>1 );
    }

    return(b);
}

main(argc,argv)
int argc;
char **argv;
{
    int num,root,last;

    last = 0;
    for ( num=1 ; num<65000 ; num++ ) {
	root = isqrt(num);
	if ( (root*root)>num ) {
	    printf("Too big!\n");
	}
	if ( ((root+1)*(root+1)) <= num ) {
	    printf("Too Small!\n");
	}
	if (last!=root) {
	    last = root;
	    printf("The square root of %4d is %3d\n",num,root);
	}
    }
}
-- 
                    umd5.UUCP    <= {seismo!mimsy,ihnp4!rlgvax}!cvl!umd5!zben
Ben Cranston zben @ umd2.UMD.EDU    Kingdom of Merryland UniSys 1100/92
                    umd2.BITNET     "via HASP with RSCS"