Question

to find square root of a number

Asked by: ashu1004

how to find square root of a number without using sqrt function

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-01-01 at 23:48:46ID20838828
Tags

square

,

root

,

find

Topic

C Programming Language

Participating Experts
8
Points
125
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Square Root in Assembly Language
    I am looking for a assembly code / algorithm for finding out the square root of a number. I am working on Intel 80196 Microcontroller. Assembly language program for any other processor will also do as I am more interested in the algorithm
  2. Square root for 8051.
    Hello, I am having a trouble with assembly language of 8051 and I need to compute a square root of 32-bit binary number. Can you help, please? Thanks.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ashu1004Posted on 2004-01-01 at 23:50:45ID: 10027905

\\\

 

by: jobrienctPosted on 2004-01-02 at 00:00:23ID: 10027925

static unsigned mborg_isqrt3(unsigned long val)
{
  unsigned long temp, g=0, b = 0x8000, bshft = 15;
  do {
    if (val >= (temp = (((g<<1)+b)<<bshft--))) {
      g += b;
      val -= temp;
    }
  } while (b >>= 1);
  return g;
}

John

 

by: shajithchandranPosted on 2004-01-02 at 00:38:24ID: 10027981

 

by: jkrPosted on 2004-01-02 at 12:08:39ID: 10030567

Hm, if this is not homework,

double dSquareRoot = pow ( <any number>, 0.5);

should do it :o)

 

by: KdoPosted on 2004-01-03 at 13:16:59ID: 10034992

Hi ashu1004,

Most square root algorithms are based on long division and require a series of guesses.  Just as the links above demonstrate, a series of guesses determines the correct value for a given digit, a bit of simple math is performed, and the guessing mechanism is repeated for the next digit.  Usually, the guesswork is reduced to the point that each guess is instinctive, but programs will have to continue the guesswork, or be table driven to eliminate guessing.  (i.e.  You and I both just "know" that the square root of 49 is 7 and that the closest square root of 66 is 8.  For the computer program to "know" all of the square roots of two digit numbers, a 100 element table will have to be devised that contains the square roots.  Alternatively, the guessing game can be used to determine these values.)

As it turns out, determining square roots is easier if you're dealing with a binary number system.  No guesswork, just simple mathematics.  This is easy to see when you're dealing with a number that is a power of two (2, 4, 8, etc...)  Simply right shift the number halfway to the right.  (Shift bit-0 0 bits, bit-1 0 bits, bit-2 1 bit, bit-3 1 bit, bit-4, 2 bits, bit-5 2 bits, etc.)  Repeated application of this rule will allow you determine the square root of values that are not powers of 2.

First, let's look at a couple of perfect squares.

49 = 7*7.  The binary representation is 110001 = 111 * 111.

Working forward, 7*7 in binary is 111 * 111.  Performing all of the cross multiplication yields:

49 = 4*(4 + 2 + 1) + 2*(4 + 2 + 1) + 1*(4 + 2 + 1)  which further expands to:

49 = (4*4 + 4*2 + 4*1) + (2*4 + 2*2 + 2*1) + (1*4 + 1*2 + 1*1)

Similarly, 144 = 12*12.  The binary representation is 10010000 = 1100 * 1100.

Again working forward, 12*12 in binary is 1100 * 1100 and performing all of the cross multiplications yields:

144 = 8*(8 + 4) + 4*(8 + 4) which expands to:

144 = (8*8 + 8*4) + (4*8 + 4*4)


Examine both of these examples carefully.  You'll note that some of the terms are squares (n*n) and some are not (n*m).  The sum of the values in each term that is a square yields the square root.

49 = (4*4 + 4*2 + 4*1) + (2*4 + 2*2 + 2*1) + (1*4 + 1*2 + 1*1)
         4*4                     +            2*2            +                     1*1
7 =    4                         +            2               +                      1

144 = (8*8 + 8*4) + (4*8 + 4*4)
           8*8            +           4*4
12 =    8               +            4

This foundation is the basis for determing the square root of values that are not perfect squares.


Consider the value 156.  It's closest square root is 12.  We can derive the integral square root by using what we learned above.

156 = 10011100 = 128 + 16 + 8 + 4

128 >> 4 + 16 >> 2 + 8 >> 2 + 4 >> 1
   8          +      4      +      2        +    2

Clearly we're looking for a number between 12 and 13 so adding all of these values yeilds a number (16) that just can't be.  What's happened is that the decimal point should occur between the second and third digit.  By adding from left to right, we simply don't add any value that causes the sum to be larger than the integral square root.


The mathematics for determining the fractional portion of the square root is a bit more complicated, but very manageable.  The algorithm supplied by jobrienct appears to calculate the integral portion of a square root using the mathematics that I've described here.

Good Luck,
Kent

 

by: jobrienctPosted on 2004-01-03 at 15:25:27ID: 10035417

well if the author didnt enjoy reading that, i sure did :)

The code I posted does exactly that, and is optimized to do it quickly on a range of cpu's. I didn't write it, I just found and posted it as a possible solution. I chose it from among several because I prefer it's method to the guessing game, which is nearly always slower.

John

 

by: sunnycoderPosted on 2004-01-03 at 23:24:34ID: 10036473

Another interesting way for integer square roots

Add up all the odd numbers from 1 while the sum is less than or equal to the number whose square root is being sought. The number of odd numbers needed is the square root.
For example, the integer square root of 23 = 4


1 + 3 + 5 + 7 = 16

1 + 3 + 5 + 7 + 9 = 25

Fast integer sqrt
long sqrt(r)
long r;
{
   long t,b,c=0;

   for (b=0x10000000;b!=0;b>>=2) {
      t = c + b;
      c >>= 1;
      if (t <= r) {
         r -= t;
         c += b;
      }
   }
   return(c);
}

But most of the times, you would be dealing with floats ... you can use one of the numerical analysis approaches (e.g. Newton's method), but they all take up some guessing
http://www.geocities.com/SiliconValley/Garage/3323/aat/a_sqrt.html

Some more methods
http://mathworld.wolfram.com/SquareRootAlgorithms.html

 

by: dmatterPosted on 2004-01-04 at 03:01:32ID: 10036760

It's far simpler than any of this...

The squareroot of any number (n) is equivalent to that number with the power of a half:

sqrt(n) == n^0.5

Hope that helps

:]

 

by: ozoPosted on 2004-01-04 at 03:15:02ID: 10036786

But in C, ^ means xor

 

by: KdoPosted on 2004-01-04 at 05:49:42ID: 10037054

Hi dmatter,

Care to demonstrate how n raised to the 1/2 power is simpler than anything else mentioned here?

Kent

 

by: jobrienctPosted on 2004-01-04 at 10:16:09ID: 10037890

Anyone else get the feeling we may have aided and abetted in homework here? <g>

John

 

by: jkrPosted on 2004-01-04 at 10:28:29ID: 10037949

>>Anyone else get the feeling we may have aided and abetted in homework here?

Check my comment :o)

 

by: dmatterPosted on 2004-01-04 at 11:07:34ID: 10038106

Hi Kdo,

I'm not sure about the mathematical proof behind it but try it with a program:

for (int i = 0; i < 100; i++)
{
   if (pow (i, 0.5) == sqrt(i))
        printf ("Checks out! \n");
   else
        printf ("Does not check out \n");
}

I think that's right..  I'd never actually use a program like this for practical uses though.

see ya

 

by: KdoPosted on 2004-01-04 at 13:32:24ID: 10038593

Hi jkr,

I'm positive that this is homework.  My response was intended to "teach", not "do".  :)


Hi dmatter,

pow() may be a single API in a C program, but the object code isn't nearly so simple.   Using pow() might solve the original poster's requirements, but the mathematics involved is at least as complicated as anything posted here.  By the way, depending on how pow() and sqrt() have been implemented your test may fail.  Floating point math (especially division) is an imprecise science on Intel chips and the least significant bits often stray so pow() and sqrt() might return slightly different answers.


Hi jobrienct,

Glad that you enjoyed reading it.  I did enjoy typing it up and actually getting to think a little bit.  It's pretty sad that the world that Micro$oft has steered us into has removed the need for most of us to think.  A while back I had to write a checksum algorithm for a partner company when they discovered that their algorithm was full of holes.  A multi-million dollar company in the mathematics business and they had to rely on "an amateur" to do the math for them.  Sad.....


Kent

 

by: jkrPosted on 2004-01-04 at 17:11:14ID: 10039342

>>Hi jkr,
>>I'm positive that this is homework.  My response was intended to "teach", not "do".  :)

Well, that I know, and you are right, appropriate and correct in your answer :o)

 

by: dmatterPosted on 2004-01-05 at 12:23:51ID: 10046662

Kdo,

Hmm, I never considered that point.  Perhaps a rounding routine could be used to elimate the LSBs (least sig bits) that may differ, although I'm pitching in the dark here - I'd have to look into it more but it doesn't rank particularly high on my agenda (Deadlines for other work are drawing near)   :?


Dave

 

by: PaulCaswellPosted on 2004-01-06 at 03:55:22ID: 10051414

All,

I've been programming for >20 years and I've never come across either of these really cute algorithms for sqrt (i.e. adding up odds and folding alternate bits). Is there a source of other cute stuff like this.

P.S. A small challenge, what does ( n ^ (n-1) ) + 1 achieve and can anyone remember ever using this in anger? (I mean '^' as in 'xor', not pow ;) ).

Paul

 

by: sunnycoderPosted on 2004-01-06 at 04:41:40ID: 10051671

gives double the value of least significant 1 in the number ?

 

by: PaulCaswellPosted on 2004-01-06 at 04:57:47ID: 10051760

Close. Its the least significant bit of a binary value.

E.G. ( 10110001000000 ^ (10110001000000 - 1) ) + 1
-> ( 10110001000000 ^ 10110000111111 ) + 1
-> 111111 + 1
-> 1000000

Anyone ever used it?

 

by: KdoPosted on 2004-01-06 at 05:00:11ID: 10051776


Good call, Sunny.

n^(n-1) is a "lobit()" function that sets all of the bits to the left of the least significant 1 bit to zero and all of the bits to the right of it to 1, creating a mask in the low end of the word.  Adding 1 simply "rounds up" to the next power of 2.


N          (N ^ (N-1)) + 1

7          (111 ^ 110) + 1
             001            + 1    = 010

14        (1110 ^ 1101) + 1
             0011             + 1 = 0100

etc...


 

by: KdoPosted on 2004-01-06 at 05:03:55ID: 10051791

Hi Paul,

You missed a bit:

E.G. ( 10110001000000 ^ (10110001000000 - 1) ) + 1
-> ( 10110001000000 ^ 10110000111111 ) + 1
>> 1111111 + 1
>> 10000000


Kent

 

by: sunnycoderPosted on 2004-01-06 at 05:09:06ID: 10051813

Thanks Kent :o)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...