Tuesday, April 23, 2024
HomeSoftware EngineeringTips on how to Discover the Subsequent Excellent Sq. in Java

Tips on how to Discover the Subsequent Excellent Sq. in Java


The problem

You would possibly know some fairly giant good squares. However what concerning the NEXT one?

Full the findNextSquare technique that finds the subsequent 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 ought to be returned. Chances are you’ll assume the parameter is non-negative.

Examples:(Enter –> Output)

121 --> 144
625 --> 676
114 --> -1 since 114 shouldn't be an ideal sq.

The answer in Java code

Possibility 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;
  }
}

Possibility 2:

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

Possibility 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));
    }    
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments