Although you are asking to do this in Bash, there is no built-in support for features such as square root or ceiling. It would be easier to delegate Perl:
perl -wmPOSIX -e "print POSIX::ceil((sqrt(1 + 8 * $n) - 1) / 2)"
Alternatively, you can use bc
to calculate the square root and some Bash to calculate the ceiling.
Define a function that prints the result of a formula with sqrt
of bc
:
formula() {
local n=$1
bc -l <<< "(sqrt(1 + 8 * $n) - 1) / 2"
}
-l
scale
0 20.
.
, , 10 / 3
3.
, .
ceil() {
local n=$1
local intpart=${n%%.*}
if [[ $n =~ \.00*$ ]]; then
echo $intpart
else
echo $((intpart + 1))
fi
}
, ,
- , ,
+ 1, .
, , :
compute() {
local n=$1
ceil $(formula $n)
}
:
check() {
local n num
for n; do
num=$(formula $n)
echo $n $num $(compute $n)
done
}
:
check 1 2 3 4 7 11 12 16 17
:
1 1.00000000000000000000 1
2 1.56155281280883027491 2
3 2.00000000000000000000 2
4 2.37228132326901432992 3
7 3.27491721763537484861 4
11 4.21699056602830190566 5
12 4.42442890089805236087 5
16 5.17890834580027361089 6
17 5.35234995535981255455 6