1
\$\begingroup\$
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please choose the minimum of your range: ");
        double minimum = scanner.nextInt();
        System.out.println("Please choose the maximum of the range: ");
        double maximum = scanner.nextInt();
        List<Double> list = new ArrayList<>();
        List<Double> doubles = new ArrayList<>();
        int sum = 0;
        for (double x = minimum; x <= maximum; x++) {
            list.add(x);
        }
        for (int i = 0; i < list.size(); i++) {
            double sqrt = Math.sqrt((i));
            doubles.add(sqrt);
        }
        for (Double value : doubles) {
            if (value.doubleValue() == value.intValue()) {
                sum += 1;
            }
        }
        System.out.println(sum);
    }
}
\$\endgroup\$
2
\$\begingroup\$

Your algorithm is inefficient:

  • Floating-point arithmetic is slower than integer arithmetic.
  • To find all the perfect squares in a range, you need only find the square root of the minimum (and round up) and the square root of the maximum (and round down).

You should be able to find the answer in constant time, with no looping.

\$\endgroup\$
2
  • \$\begingroup\$ @mdfst13 I was misled by the variable named sum, which would have been better named count. \$\endgroup\$ – 200_success Mar 18 '17 at 16:55
  • \$\begingroup\$ the program counts how many perfect squares are present in a given range. In hindsight, count would have been a better variable, but English is my fifth language \$\endgroup\$ – EastXWest Mar 18 '17 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.