HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Square root implementations

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationsrootsquare

Problem

The question was:


Write a function that calculates the root of a given number.

  • Answer A = I wrote it for integers. just run up to half of the number



  • Answer B+C = are for double, using Newton's law.



I just implemented this in C#.

They all work and were tested.Please comment me about anything from not well written code, complexity, style, or give a better solution.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class FindSquareRoot
    {
        public FindSquareRoot()
        {
            int numberToFind = 49;
            int res = SquareRoot(numberToFind);
            Console.WriteLine(res);

            double doubleNumberToFind = 157.0;
            double resDouble = SquareRoot(doubleNumberToFind);
            Console.WriteLine(resDouble);
            resDouble = SquareRootBetter(doubleNumberToFind);
            Console.WriteLine(resDouble);
        }

        public int SquareRoot(int number)
        {
            int half = number / 2;
            int counter = 0;
            while (counter  precision )
            {
                if(Math.Pow(mid,2) > number)
                {
                    high = mid;
                }else
                {
                    low = mid;
                }
                prev = mid;
                mid = (low+high)/ 2.0;
            }
            return mid;
        }
        public double SquareRootBetter(double number)
        { 
            double precision = 10e-8;
            double prev = 0.0;
            double mid = number;
            while(Math.Abs(mid - prev ) > precision)
            {
                prev = mid;
                mid = (mid +(number/ mid))/2.0;
            }
            return mid;
        }    
    }
}

Solution

-
SquareRoot(int)

-
returns half if the integer is not a perfect square. A very dubious decision. I'd consider returning a best integer approximation, or throwing an exception.

-
uses a linear search. A binary search would be quite faster. A Newton-Raphson (yes it works with integers) would be even factor.

-
An error approximation is better done as Math.abs(number - Math.pow(candidate_square_root, 2))

Context

StackExchange Code Review Q#71596, answer score: 6

Revisions (0)

No revisions yet.