Software Engineering

How you can Discover the Subsequent Good Sq. in Java

How you can Discover the Subsequent Good Sq. in Java
Written by admin


The problem

You would possibly know some fairly massive good squares. However what in regards to the NEXT one?

Full the findNextSquare technique that finds the following integral good sq. after the one handed as a parameter. Recall that an integral good sq. is an integer n such that sqrt(n) can also be an integer.

If the parameter is itself not an ideal sq. then -1 must be returned. It’s possible you’ll assume the parameter is non-negative.

Examples:(Enter –> Output)

121 --> 144
625 --> 676
114 --> -1 since 114 will not be an ideal sq.

The answer in Java code

Choice 1:

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

Choice 2:

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

Choice 3:

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

Check circumstances to validate our resolution

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

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

About the author

admin

Leave a Comment