liveBook · Manning

Integer square root

As explained in .NET in Action, Second Edition

An integer square root is a square root whose result is an integer.

An integer square root is a square root whose result is an integer. For Sudoku, the board size must be a perfect square so its rows and columns can be divided into equal blocks; valid examples include 4, 9, 16, and 25. section 6.3

A practical validation check follows these steps:

  • Require a square board and reject sizes below 4. section 6.6
  • Compute the truncated square root with (int)Math.Sqrt(rows). section 6.6
  • Multiply the truncated result by itself and compare it with the original size; unequal values indicate a non-integer square root. section 6.6
  • Test representative boundaries and invalid values rather than attempting every possible integer-sized board. section 6.6
Listing 6.13 Checking whether the board size is correct
public bool IsValid()
{
  int rows = _board.GetLength(0);     #1
  int cols = _board.GetLength(1);     #2
  
  if (rows != cols)                   #3
    return false;
  
  if (rows < 4)                       #4
    return false;
  
  int sqrt = (int)Math.Sqrt(rows);    #5
  if ((sqrt * sqrt) != rows)          #6
    return false;
  
  return true;                        #7
}

Shows the complete C# board-size check, including square-dimension validation, minimum size, Math.Sqrt conversion, and square reconstruction. section 6.6

Listing 6.12 A Theory test that checks empty boards of different sizes
[Theory]                                              #1
[InlineData(0, false)]                                #2
[InlineData(1, false)]
[InlineData(4, true)]
[InlineData(8, false)]
[InlineData(9, true)]
[InlineData(10, false)]
[InlineData(16, true)]
public void EmptyBoardSizes(int size, bool isValid)   #3
{
  int[,] empty = new int[size, size];                 #4
  var solver = new Solver(empty);
  Assert.Equal(isValid, solver.IsValid());            #5
}

Demonstrates an xUnit Theory using inline data for valid perfect squares, invalid sizes, and boundary cases. section 6.6

How .NET in Action, Second Edition covers it

How deep it goes
Defines the condition and implements it with Math.Sqrt and multiplication, then tests bounds and representative invalid values.
Examples
Uses board sizes 4, 9, 16, and 25 as valid examples, with 0, 1, 8, and 10 as test inputs.
What it assumes
Assumes C# array and unit-testing familiarity while teaching the square-root condition through Sudoku validation.
What you can do after
Apply it via System.Math and xUnit to validate Sudoku dimensions and cover representative size cases.
How it connects
Connects integer square roots to Sudoku, square arrays, System.Math, and xUnit theory tests.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.