Find Square root of number only with addition or/and subtraction My problem is following: I want to Find Square root of a number (which is the square of integer) only with addition or subtraction (or together). I wrote the algorithm which works, but I am really interested in what will be better solution to solve this problem.

static void FindSquareRoot(int S)
{
    int i = 1;

    for (; i &lt;= S; i++)
    {
        int k = S;
        int j = i;

        while (j&gt;0)
        {
            k = k - i;
            j--;
        }

        if (k == 0)
        {
            Console.WriteLine("Square root of {0} is {1}", S, i);
            break;
        }
        else if (k &lt; 0)
        {
            Console.WriteLine("Not found");
            break;
        }
    }
}


The basic idea of this algorithm is to choose one number(i) and subtract it from S (i) times. if the result will be 0, then it means that this(i) is the number I was looking for..
static void FindSquareRoot(int S)



Why void? The method would be more useful if it returned the value rather than printing it, and throw an exception if the input was invalid rather than printing an error message.




    int i = 1;

    for (; i &lt;= S; i++)



The scope of i is the loop, so why not restrict it to that scope?




        int k = S;
        int j = i;

        while (j&gt;0)
        {
            k = k - i;
            j--;
        }



i and j as loop variables are fairly conventional, but what does k mean? It's not a loop variable. A comment indicating that after the inner loop k = S - i * i would help, and might suggest a name like surplus.

Again, restrict the scope of the loop variable to the loop unless there's good reason not to.



Finally, on scope, by pulling k out of the loop you should be able to figure out a way to update its value without using an inner loop...