Home > database >  Write a program that takes a command-line argument n and prints the nth harmonic number using shell
Write a program that takes a command-line argument n and prints the nth harmonic number using shell

Time:07-28

since harmonic numbers include fractions and i dont know how to use fractions in the program , hence i am getting error. Kindly advise

Below is the program i tried-->>>

#!/bin/bash -x

read -p "Enter a number:" n
totalharmonic=0


for((count=1;count<=$n;count  ))
do

harmonic=$((1/$count))
totalharmonic=$(($harmonic   $totalharmonic));
done

echo "nth harmonic number is $totalharmonic"

CodePudding user response:

Don't use bash arithmetic (integer only) for floating point computations. Use for instance bc or awk or python... Example with bc and a 10 digits precision:

$ n=20
$ printf 'scale=10; h=0; for(c=1; c<=%d; c  ) h =1/c; h\n' "$n" | bc
3.5977396567

Example with awk:

$ awk -v n=20 'END {for(c=1; c<=n; c  ) h =1/c; printf("%.10f\n", h)}' /dev/null
3.5977396571

CodePudding user response:

Fractions under

Unfortunely, you can't work with real number under .

Pure basħ solution: pseudo integer.

As could only work with integers, but with 64bits!! You could shift big integer to emulate pseudo floating point.

#!/bin/bash

read -p "Enter a number:" n

for ((v=10**16,to=0,cnt=1;cnt<=n;to =v/cnt  )){ :;}
to=${v:1}$to
printf -v to %.14f ${to::-16}.${to: -16}
echo "nth '$n' harmonic number is $to"
./harmonic  <<<20
nth '20' harmonic number is 3.59773965714368

Regular way using binary calculator bc

For this, you have to use binary calculator bc:

#!/bin/sh

read -p "Enter a number:" n
bcStr='total=0'
count=1
while [ $count -le $n ] ;do
    bcStr="$bcStr;total =1/$count"
    count=$((count 1))
done
totalharmonic=$(echo "$bcStr;total"|bc -l)
echo "nth '$n' harmonic number is $totalharmonic"
./harmonic  <<<20
nth '20' harmonic number is 3.59773965714368191144

Under you could

#!/bin/bash

read -p "Enter a number:" n
bcStr='total=0'
for (( count=1 ; count <= n ; count   )) {
    bcStr =";total =1/$count"
}
read totalharmonic < <(bc -l <<<"$bcStr;total")
echo "nth '$n' harmonic number is $totalharmonic"

Or making whole loop under bc:

#!/bin/sh

read -p "Enter a number:" n
bc -l <<eof
    tot=0;
    for ( cnt=1 ; cnt <= $n ; cnt   ) tot =1/cnt;
    print "nth '$n' harmonic number is ";
    tot
eof
./harmonic  <<<20
nth '20' harmonic number is 3.59773965714368191144
  • Related