Monday, February 20, 2023
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 Resolution {
  public static String findSquares(closing int n) {
    closing lengthy a = (n + 1) / 2;
    closing lengthy b = a - 1;
    return String.format("%d-%d", a * a, b * b);
  }
}

Possibility 2:

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

Possibility 3:

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

Take a look at circumstances to validate our resolution

import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Take a look at
    public void testBasicNumbers() {
        assertEquals("25-16",Resolution.findSquares(9));
    }
    @Take a look at
    public void testSmallerNumbers() {
        assertEquals("1-0",Resolution.findSquares(1));
    }
    @Take a look at
    public void testBiggerNumbers() {
        assertEquals("891136-889249",Resolution.findSquares(1887));
        assertEquals("2499600016-2499500025",Resolution.findSquares(99991));
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments