How to Find the Next Perfect Square in Java


The challenge

You might know some pretty large perfect squares. But what about the NEXT one?

Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.

If the parameter is itself not a perfect square then -1 should be returned. You may assume the parameter is non-negative.

Examples:(Input –> Output)

121 --> 144
625 --> 676
114 --> -1 since 114 is not a perfect square

The solution in Java code

Option 1:

public class NumberFun {
  public static long findNextSquare(long sq) {
      long root = (long) Math.sqrt(sq);
      return root * root == sq ? (root + 1) * (root + 1) : -1;
  }
}

Option 2:

public class NumberFun {
  public static long findNextSquare(long sq) {
      long result; 
      double d = Math.sqrt(sq);
      if ( d % 1  == 0) result = (long) Math.pow(++d, 2);
      else result = -1;
      return result;
  }
}

Option 3:

public class NumberFun {
  public static long findNextSquare(long sq) {
      Double side = Math.sqrt(sq);
      return (side % 1 > 0) ? -1 : (long) Math.pow(side + 1, 2);
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class FindNextSquareTest {
    @Test
    public void test1() {
        assertEquals(144, NumberFun.findNextSquare(121));
    }
    
    @Test
    public void test2() {
        assertEquals(676, NumberFun.findNextSquare(625));
    }
    
    @Test
    public void test3() {
        assertEquals(-1, NumberFun.findNextSquare(114));
    }    
}