recursion square root

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • game2d
    New Member
    • Apr 2013
    • 59

    recursion square root

    how to test if a num is a square root?
    ex: 9 is square root
    3 is not square root
    /////////////////////////////////////////////
    Code:
    x = 0; //always start at 0
    y = 101010;  //is this a square root?
    square(x, y){
         if((x*x) >= y){       //not a square root
             return false;
         }
         else if((x*x) == y)    //it is a square root
             return true;
         }
         else{                 //inc x by 1
            square(x+1, y);
         }
    }
    this algorithm works fine when y is small int. ex 4, 10, 20.
    but when i put y to be large ex 10000. than i get it to problem.
    this is bc x start out with 0 and slowing get inc by 1. this takes alot of time.

    is there better way to do this by using recursion? may be there is some formula that i dont know about.
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    change the increment part.....

    start with increments of i.e. 100
    if x*x>y (not x*x>=y), than do :
    x=x-100, and change increments to 10

    or, if google, and find this

    Comment

    • game2d
      New Member
      • Apr 2013
      • 59

      #3
      i am not sure how to do this part: x=x-100, and change increments to 10

      Code:
      x = 100; //always start at 0
      y = 101010;  //is this a square root?
      square(x, y){
           if((x*x) > y){       //not a square root
               return false;
           }
           else if((x*x) == y)    //it is a square root
               return true;
           }
           else{                 //inc x by 1
              square(x+1, y);
           }
      }

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        Well, there are a few things you could do. Personally, I'd have a look at the so called Babylonian method for computing square roots; it's quite simple and relatively easy to implement in a recursive manner. Also, it should be much faster than your current method.

        Comment

        Working...