Harmonic series: Difference between revisions

Added Tcl version
(Added Tcl version)
Line 2,448:
Position of first term > 10 is 12367
</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl># Task 1
proc harmonic {n} {
if {$n < 1 || $n != [expr {floor($n)}]} {
error "Argument to harmonic function is not a natural number"
}
set Hn 1
for {set i 2} {$i <= $n} {incr i} {
set Hn [expr {$Hn + (1.0/$i)}]
}
return $Hn
}
 
# Task 2
for {set x 1} {$x <= 20} {incr x} {
set Hx [harmonic $x]
puts "$x: $Hx"
}
 
# Task 3 /stretch
set x 0
set lastInt 1
while {$lastInt <= 10} {
incr x
set Hx [harmonic $x]
if {$Hx > $lastInt} {
puts -nonewline "The first harmonic number above $lastInt"
puts " is $Hx at position $x"
incr lastInt
}
}
</syntaxhighlight>
{{out}}
<pre>1: 1
2: 1.5
3: 1.8333333333333333
4: 2.083333333333333
5: 2.283333333333333
6: 2.4499999999999997
7: 2.5928571428571425
8: 2.7178571428571425
9: 2.8289682539682537
10: 2.9289682539682538
11: 3.0198773448773446
12: 3.103210678210678
13: 3.180133755133755
14: 3.251562326562327
15: 3.3182289932289937
16: 3.3807289932289937
17: 3.439552522640758
18: 3.4951080781963135
19: 3.547739657143682
20: 3.597739657143682
The first harmonic number above 1 is 1.5 at position 2
The first harmonic number above 2 is 2.083333333333333 at position 4
The first harmonic number above 3 is 3.0198773448773446 at position 11
The first harmonic number above 4 is 4.02724519543652 at position 31
The first harmonic number above 5 is 5.002068272680166 at position 83
The first harmonic number above 6 is 6.004366708345567 at position 227
The first harmonic number above 7 is 7.001274097134162 at position 616
The first harmonic number above 8 is 8.000485571995782 at position 1674
The first harmonic number above 9 is 9.000208062931115 at position 4550
The first harmonic number above 10 is 10.000043008275778 at position 12367</pre>
 
=={{header|Verilog}}==
31

edits