'Java Heap Space error while writing a program for Square root of an Integer

I am trying to find out the square root of an integer, but in case the integer value is too large for instance - 2147395599. Then the following program gives this exception.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at com.aakash.BinarySearch.SquareRoot.mySqrt(SquareRoot.java:12)
    at com.aakash.BinarySearch.SquareRoot.main(SquareRoot.java:8)

Process finished with exit code 1

Square root Program

package com.aakash.BinarySearch;

import java.util.Arrays;

public class SquareRoot {

    public static void main(String[] args) {
            int ans = mySqrt(2147395599);
        System.out.println(ans);
    }
    public static int mySqrt(int x) {
        int[] arrayUpton = new int[x];
        int start =0;
        int end = arrayUpton.length-1;
        int mid =  start + (start-end)/2;

        for (int index = start; index <= end; index++) {
            arrayUpton[index]=index+1;
        }

        for (int index = start; index < end; index++) {
            if(arrayUpton[index]*arrayUpton[index]==x){
                return arrayUpton[index];
            } else if (arrayUpton[index]*arrayUpton[index]>x) {
                return arrayUpton[index-1];
            }
        }
        return 0;
    }

}



Solution 1:[1]

You are attempting to allocate an array of nearly 2^31 integers. That will occupy 8GB which is (evidently) too large for your JVMs heap. (And it could well be too large for your computer.)

But your real problem is your algorithm.

You don't need to allocate a huge array to calculate integer square roots. Even if you do it by searching all (positive) int values.

Consider this: your code carefully sets each of the array elements to a number that is one greater than the array subscript. And then it retrieves the values from the array to use them. But if you know that arrayUpton[i] contains i + 1 ... you don't need to retrieve it. Just add 1 to i instead of fetching the (same) value from the array.

In addition:

  • Irrespective of the tag, your algorithm isn't implementing a binary search.
  • I'm not even convinced the algorithm will work.

I suggest you do some Googling to see if you can find a better integer square root algorithm.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1