This module contains procedures and generic interfaces for computing the square root of integers.
In number theory, the integer square root (getSqrt) of a non-negative integer \(n\) is the non-negative integer \(m\) which is the greatest integer less than or equal to the square root of \(n\),
\begin{equation}
\mbox{getSqrt}(n) = \lfloor{\sqrt{n}}\rfloor ~.
\end{equation}
For example,
\begin{equation}
\mbox{getSqrt}(27) = \lfloor{\sqrt{27}}\rfloor = \lfloor 5.19615242270663\ldots \rfloor = 5 ~.
\end{equation}
Two methods of finding the integer square root include linear and binary search, both of which are implemented by the procedures of this module.
- Note
- While the procedures of this module return
getSqrt(n)
, the greatest integer less than or equal to the square root of a given integer, one can readily compute the smallest integer a
greater than or equal to the square root of n
as a = 1 + getSqrt(n - 1)
.
This number is equivalent to the ceiling of the exact square root of n
.
- Benchmarks:
Benchmark :: The runtime performance of getSqrt for integer
vs. real
input ndim
. ⛓
8 use iso_fortran_env,
only:
error_unit
13 integer(IK) :: iposint
14 integer(IK) :: fileUnit
15 integer(IKG) :: intSqrt, dumm
16 integer(IKG) ,
allocatable :: posint(:)
17 type(bench_type) ,
allocatable :: bench(:)
19 bench
= [
bench_type(name
= SK_
"getSqrtBinary", exec
= getSqrtBinary, overhead
= setOverhead)
&
20 ,
bench_type(name
= SK_
"getSqrtLinear", exec
= getSqrtLinear, overhead
= setOverhead)
&
21 ,
bench_type(name
= SK_
"floor_sqrt", exec
= floor_sqrt, overhead
= setOverhead)
&
24 write(
*,
"(*(g0,:,' '))")
25 write(
*,
"(*(g0,:,' vs. '))") (bench(ibench)
%name, ibench
= 1,
size(bench))
26 write(
*,
"(*(g0,:,' '))")
28 open(newunit
= fileUnit, file
= "main.out", status
= "replace")
30 write(fileUnit,
"(*(g0,:,','))")
"Integer", (bench(ibench)
%name, ibench
= 1,
size(bench))
32 loopOverArraySize:
do iposint
= 1,
size(posint)
34 write(
*,
"(*(g0,:,' '))")
"Benchmarking with posint = ", posint(iposint)
35 do ibench
= 1,
size(bench)
36 bench(ibench)
%timing
= bench(ibench)
%getTiming(minsec
= 0.04_RK)
38 write(fileUnit,
"(*(g0,:,','))") posint(iposint), (bench(ibench)
%timing
%mean, ibench
= 1,
size(bench))
40 end do loopOverArraySize
41 write(
*,
"(*(g0,:,' '))") dumm
42 write(
*,
"(*(g0,:,' '))")
52 subroutine setOverhead()
60 subroutine getSqrtBinary()
62 intSqrt
= getSqrt(posint(iposint), binary)
66 subroutine getSqrtLinear()
68 intSqrt
= getSqrt(posint(iposint), linear)
72 subroutine floor_sqrt()
73 intSqrt
= floor(
sqrt(
real(posint(iposint),
RK)), IKG)
Generate count evenly-logarithmically-spaced points over the interval [base**logx1,...
Generate and return a vector of unique values in the input array.
Generate and return an object of type timing_type containing the benchmark timing information and sta...
Generate and return the integer square root of an input non-negative integer.
This module contains procedures and generic interfaces for generating arrays with linear or logarithm...
This module contains procedures and generic interfaces for finding unique values of an input array of...
This module contains abstract interfaces and types that facilitate benchmarking of different procedur...
This module defines the relevant Fortran kind type-parameters frequently used in the ParaMonte librar...
integer, parameter RK
The default real kind in the ParaMonte library: real64 in Fortran, c_double in C-Fortran Interoperati...
integer, parameter LK
The default logical kind in the ParaMonte library: kind(.true.) in Fortran, kind(....
integer, parameter IK
The default integer kind in the ParaMonte library: int32 in Fortran, c_int32_t in C-Fortran Interoper...
integer, parameter SK
The default character kind in the ParaMonte library: kind("a") in Fortran, c_char in C-Fortran Intero...
This module contains procedures and generic interfaces for computing the square root of integers.
This is the class for creating benchmark and performance-profiling objects.
Example Unix compile command via Intel ifort
compiler ⛓
3ifort -fpp -standard-semantics -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
Example Windows Batch compile command via Intel ifort
compiler ⛓
2set PATH=..\..\..\lib;%PATH%
3ifort /fpp /standard-semantics /O3 /I:..\..\..\include main.F90 ..\..\..\lib\libparamonte*.lib /exe:main.exe
Example Unix / MinGW compile command via GNU gfortran
compiler ⛓
3gfortran -cpp -ffree-line-length-none -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
Postprocessing of the benchmark output ⛓
3import matplotlib.pyplot
as plt
8dirname = os.path.basename(os.getcwd())
12df = pd.read_csv(
"main.out", delimiter =
",")
13colnames = list(df.columns.values)
19ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
22for colname
in colnames[1:]:
23 plt.plot( df[colnames[0]].values
28plt.xticks(fontsize = fontsize)
29plt.yticks(fontsize = fontsize)
30ax.set_xlabel(colnames[0], fontsize = fontsize)
31ax.set_ylabel(
"Runtime [ seconds ]", fontsize = fontsize)
32ax.set_title(
" vs. ".join(colnames[1:])+
"\nLower is better.", fontsize = fontsize)
36plt.grid(visible =
True, which =
"both", axis =
"both", color =
"0.85", linestyle =
"-")
37ax.tick_params(axis =
"y", which =
"minor")
38ax.tick_params(axis =
"x", which =
"minor")
39ax.legend ( colnames[1:]
46plt.savefig(
"benchmark." + dirname +
".runtime.png")
52ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
55for colname
in colnames[1:]:
56 plt.plot( df[colnames[0]].values
57 , df[colname].values / df[colnames[1]].values
61plt.xticks(fontsize = fontsize)
62plt.yticks(fontsize = fontsize)
63ax.set_xlabel(colnames[0], fontsize = fontsize)
64ax.set_ylabel(
"Runtime compared to {}".format(colnames[1]), fontsize = fontsize)
65ax.set_title(
"Runtime Ratio Comparison. Lower means faster.\nLower than 1 means faster than {}().".format(colnames[1]), fontsize = fontsize)
69plt.grid(visible =
True, which =
"both", axis =
"both", color =
"0.85", linestyle =
"-")
70ax.tick_params(axis =
"y", which =
"minor")
71ax.tick_params(axis =
"x", which =
"minor")
72ax.legend ( colnames[1:]
79plt.savefig(
"benchmark." + dirname +
".runtime.ratio.png")
Visualization of the benchmark output ⛓
Benchmark moral ⛓
- The benchmark procedures named
getSqrtBinary
and getSqrtLinear
call the generic interface getSqrt with a method
argument of type binary_type and linear_type respectively.
- From the benchmark results it appears that the binary search algorithm for computing the integer square root is significantly faster than the linear search method.
The binary search algorithm is also faster than the naive approach based on the formula floor(sqrt(real(posint, RK)))
.
- Test:
- test_pm_mathSqrt
Final Remarks ⛓
If you believe this algorithm or its documentation can be improved, we appreciate your contribution and help to edit this page's documentation and source file on GitHub.
For details on the naming abbreviations, see this page.
For details on the naming conventions, see this page.
This software is distributed under the MIT license with additional terms outlined below.
-
If you use any parts or concepts from this library to any extent, please acknowledge the usage by citing the relevant publications of the ParaMonte library.
-
If you regenerate any parts/ideas from this library in a programming environment other than those currently supported by this ParaMonte library (i.e., other than C, C++, Fortran, MATLAB, Python, R), please also ask the end users to cite this original ParaMonte library.
This software is available to the public under a highly permissive license.
Help us justify its continued development and maintenance by acknowledging its benefit to society, distributing it, and contributing to it.
- Copyright
- Computational Data Science Lab
- Author:
- Amir Shahmoradi, April 23, 2017, 1:36 AM, Institute for Computational Engineering and Sciences (ICES), University of Texas at Austin