delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/03/17/01:46:45

From: James W Sager Iii <sager+@andrew.cmu.edu>
Newsgroups: comp.os.msdos.djgpp
Subject: So I coded up my own square root function
Date: Sat, 17 Mar 2001 01:28:39 -0500
Organization: Carnegie Mellon, Pittsburgh, PA
Lines: 81
Message-ID: <wugkELu00UjD8Q1EVI@andrew.cmu.edu>
NNTP-Posting-Host: po8.andrew.cmu.edu
X-Trace: bb3.andrew.cmu.edu 984810769 1667 128.2.10.108 (17 Mar 2001 06:32:49 GMT)
X-Complaints-To: advisor AT andrew DOT cmu DOT edu
NNTP-Posting-Date: 17 Mar 2001 06:32:49 GMT
X-Added: With Flames (outnews v2.6)
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Stupid djgpp isn't doing sqrt right so I made my own.

Its processing time is like O log(n) or so.

Returns an integer square root value within 1.


#include <iostream.h>


int ghettosqr(int square);



void main(void)
{
int a;
cout<<endl;

a=ghettosqr(10001);

cout<<a;
}

int ghettosqr(int square)
{
//A keeps track of a guess for the square root
int a=1;
//add keeps track off how much to add/subtract to A it.
float add=1;
//1=add -1 = sub depending
int addsub=1;
//A little extra factor that makes sure everything is decrementing
float divisor=1;

if(square == 1)
return 1;

if(square < 1)
return 0;

while(1)
{
//Return statements

if((a*a) == square )
return a;
if((a*a) > square )
if(((a-1)*(a-1)) < square )
return a;
if((a*a) < square )
if(((a+1)*(a+1)) > square )
return a;


//If incrementing and the guess is over estimated reverse the binary search
if(addsub == 1)
if(a*a > square)
{
//if(add < 2)
//return a;
add=add/4;
addsub=-1;
divisor = divisor * 1.1;
}

//If decrementing and the guess is under estimated reverse the binary search
if(addsub == -1)
if(a*a <square)
{
add=add/4;
addsub=1;
divisor = divisor * 1.1;
}
//change guess in the right direction
a=a+add*addsub;
//change binary search acceleration
add=add+add/divisor;
}
}

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019