-1

Use the Java Math square root method to calculate square roots from 1 to 1,000. The output the whole numbers only.Do not start by calculating squares and then printing out that number's square root. Calculate all square roots and determine if they are whole numbers.

I looked up several answers that seemed to dance around the solution but none of them so very concise. Here is what I have so far.

public class Assignment9
{
    public static void main(String[] args)
    {
        double root = 1;
        double sqrt = Math.sqrt(root);

        do
        {
            if(sqrt % 1 == 0)
            {
                System.out.printf("%.0f\t%.0f%n", root, Math.sqrt(root));
                root++;
            }
        }
        while(root <= 1000);
    }
}

The output is printing the square roots but keeps rounding up each number. I want to only print out one number per perfect square, (e.g. 1 1, 4 2, 9 3, etc). I understand the question, but every time I run the program I get this as my output:

     1 1
     2 1
     3 2
     4 2
     5 2
     6 2
     7 3
     8 3
     9 3
     10 3
     ...
     1000 32
azurefrog
  • 10,785
  • 7
  • 42
  • 56
  • What's up with your indentation? – khelwood Jun 17 '16 at 15:20
  • 3
    since you know in advance when to stop, use the for loop instead of do..while. You will spare a increment operation. – spi Jun 17 '16 at 15:20
  • Although this is unrelated to your problem, you'll have an easier time coding by using the for and while loops more often than the do-while loop. They give you more control over how you iterate in an easier-to-use format. – Everyone_Else Jun 17 '16 at 17:49
  • Have a look at http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer?rq=1 for additional resources. – andand Jun 18 '16 at 02:19

2 Answers2

2

You aren't updating the value sqrt. It's always just 1, and thus sqrt % 1 is always 0.

johmsp
  • 296
  • 1
  • 8
1

Since this is obviously an assignment, I'd rather give some hints instead of the solution.

Important points to think about:

  • Think of how sqrt is updated in the loop.
  • Whenever sqrt % 1 == 0 is false, what happens to root (and how does it affect the loop?)

Minor points:

  • Do you really need root to be a double?
κροκς
  • 592
  • 5
  • 18