How to find the harmonic value of N (1 + 1/2 + 1/3 + ... 1/N) in Scala

1 Answer

0 votes
// harmonic value of N  = (1 + 1/2 + 1/3 + ... 1/N)

def getHarmonicValue(n: Int): Double = {
    var hv = 0.0
    
    for (i <- 1 to n) {
        hv += 1.0 / i
    }
    
    hv
}

def getHarmonicValueRecursion(n: Int): Double = {
    if (n == 1) {
        1.0
    } else {
        1.0 / n + getHarmonicValueRecursion(n - 1)
    }
}

val n = 6

println("Harmonic value: " + getHarmonicValue(n))
println("Harmonic value: " + getHarmonicValueRecursion(n))

  
  
     
/*
run:
     
Harmonic value: 2.4499999999999997
Harmonic value: 2.4499999999999997
     
*/

 



answered Nov 2, 2024 by avibootz
...