How to perform this calculation and bring it to standard?

I am trying to do this in bash:

read n

echo int(math.ceil((math.sqrt(1 + 8 * n) - 1) / 2))

Of course, this is not working syntax, but I just put it there so you can tell what I'm trying to do.

Is there an easy way to make this a valid bash?

+4
source share
3 answers

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 bcto calculate the square root and some Bash to calculate the ceiling.

Define a function that prints the result of a formula with sqrtof 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
+2

bc sqrt.

echo "(sqrt(1 + 8 * 3) - 1) / 2" | bc

Ceil , .

Ceil integer

,

  ceiling_divide() {
      ceiling_result=`echo "($1 + $2 - 1)/$2" | bc`
    }
+1

You can use bc for the whole job

$>cat filebc

print "Enter a number\n";
scale=20
a=read()
b=((sqrt(1 + 8 * a) - 1) / 2)
scale=0
print "ceil = ";
((b/1)+((b%1)>0))
quit

Call him that

bc -q filebc
+1
source

Source: https://habr.com/ru/post/1689145/


All Articles