Philip Santana Dias
Philip Santana Dias

Reputation: 19

Output the square root just for the whole numbers

I need to Output the results of square root just for the whole numbers.

Example:

1  - 1
4  - 2
9  - 3
16 - 4...

up to 961 - 31... Which is the last square root before 1000.

Until now I have this... But, this is showing square roots for all numbers until 1000, and I want the square root for WHOLE NUMBERS ONLY.

What should I do?

public class HelloWorld {
    public static void main(String args[]) {
        double i = 1;
        do {
            System.out.printf("%.0f\t%.0f\n", i, Math.sqrt(i));
            i++;
        } while (i <= 1000);
    }
}

The output that I want should look like this:

enter image description here

Upvotes: 0

Views: 2824

Answers (4)

Mixone
Mixone

Reputation: 1326

Your method of solving this problem is slightly flawed.

  • You can know the biggest number immediately, it is the floor of the square root of the limit you have. So for 1000 => sqrt(1000) = 31.6.... therefore the closest you will get with a whole number is 31 squared, anything bigger will be greater than 1000
  • Also, you have a function, f(x) = x^2 , but you are looping through f(x) values instead of x values, this will make for a much larger amount of tests.

I would just do:

for(int i = 0; i < Math.sqrt(1000); i++) {
    System.out.println((i+1)^2 + " - " + i);
}

Upvotes: 0

Johny
Johny

Reputation: 2188

Try this solution

for (int i = 1; i <= 1000; i++) {
    double sqrt = Math.sqrt(i);
    if (sqrt % 1 == 0) {
        System.out.println(i + " " + (int) sqrt);
    }
}

For int values sqrt % 1 will be equal to zero.

Upvotes: 0

The trick that can solve your request is in the Math class too,

Math.floor(...) 

that method will round a double to the lower integer, so you need to check if the root and the lower floor are the same..

Example:

for (int j = 0; j < 1000; j++) {
            final double res = Math.sqrt(j);
            if (res == Math.floor(res)) {
                System.out.printf("%d\t%.0f\n", j, res);
            }
        }

Upvotes: 1

M.S.
M.S.

Reputation: 1091

It is not efficient to loop through all 1000 values. Instead, consider the following code:

for(int i = 1; i <= Math.sqrt(1000); i++) {
    System.out.println(i*i + " - " + i);
}

Upvotes: 1

Related Questions