Wednesday, February 21, 2024
HomeSoftware EngineeringHow you can Discover the Squares in Java

How you can Discover the Squares in Java


The problem

Full the perform that takes an odd integer (0 < n < 1000000) which is the distinction between two consecutive excellent squares, and return these squares as a string within the format "bigger-smaller".

Examples

9  -->  "25-16"
5  -->  "9-4"
7  -->  "16-9"

The answer in Java code

Possibility 1:

public class Answer {
  public static String findSquares(last int n) {
    last lengthy a = (n + 1) / 2;
    last lengthy b = a - 1;
    return String.format("%d-%d", a * a, b * b);
  }
}

Possibility 2:

interface Answer {
  static String findSquares(lengthy n) {
    return (n /= 2) * n + 2 * n + 1 + "-" + n * n;
  }
}

Possibility 3:

public class Answer{
  public static String findSquares(int n){
    lengthy n1 = n/2;
    lengthy n2 = n1+1;
    return String.valueOf(n2*n2)+"-"+ String.valueOf(n1*n1);
  }
}

Check circumstances to validate our answer

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

public class SolutionTest {
    @Check
    public void testBasicNumbers() {
        assertEquals("25-16",Answer.findSquares(9));
    }
    @Check
    public void testSmallerNumbers() {
        assertEquals("1-0",Answer.findSquares(1));
    }
    @Check
    public void testBiggerNumbers() {
        assertEquals("891136-889249",Answer.findSquares(1887));
        assertEquals("2499600016-2499500025",Answer.findSquares(99991));
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments