Algorithm finding square roots one digit at a time

For this program we are making three algorithms to find square roots, I got the first one done, but I'm lost on the second, I think I am pretty close but while it finds the correct square root for 16 for example, it does not for 5; giving a value of 2.15 rather than the correct value of 2.2360679775

Instructions given are "The second algorithm finds the root one digit at a time. You will do this by running a for loop from 0 through 14 to select each digit and inside this loop will be a for loop running from 0 to 9 that works through all the possible values of each digit. You will need to track the decimal portion of the process independently of the digit value. For example,the 1st digit will be the for loop digit times 1e0. The 2nd digit will be the for loop digit times 1e-1. Do this all the way to the 15th digit which will be the for loop digit times 1e-14. Keep in mind that you have an accurate guess that you are adding to. The added value may be too small or too large. You'll have to break out of the inner loop at the appropriate place. This algorithm is fairly straight forward and will not enter into an infinite loop."

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;

int main()
{

  double root, temp, rootAnswer;
  cout << "Enter Number\n";
  cin >> root;
  for (int n=0; n<=14; n++)
  {
       for (int i = 0; i<= 9;i++)
       {
            temp = (i * i) * pow(10,-n);
          if ((rootAnswer + temp)*(rootAnswer + temp) > root)
          {
            temp = (i-1) * (i-1) * pow(10,-n);
            rootAnswer = rootAnswer + temp ;
            break;
          }
       }
    }

  cout << "Root answer is: " << rootAnswer << endl;
}
You are squaring the digit twice.

Change (i * i) to just i

Change (i-1) * (i-1) to just (i-1)

Also, rootAnswer hasn't been initialised. Initialise it to, err, 0, but see my last comment below.


This is not a good approach.
- You are wastefully calculating the same thing several times.
- It is better to do successive divisions of a factor by 10 (just once per n loop) than repeated calls to pow(10,-n). Actually, you can get the next digit by repeat adding rather than new multiplies.
- You may be calculating things to 14 decimal digits, but you aren't writing them to more than 6 sig figs.
- Your program won't work if the number is greater than or equal to 100.
Last edited on
hmm its a simple enough program but finding it one digit at a time is harder than just finding it with any of several methods (ignoring pow to the 1/2 or sqrt type instant answer solutions). Interesting approach... never would have crossed my mind to try to zero in on it one digit at a time.
Topic archived. No new replies allowed.