Harmonic series: Difference between revisions
Content deleted Content added
ReeceGoding (talk | contribs) Added R. |
ReeceGoding (talk | contribs) →{{header|R}}: Alternative solution. |
||
Line 1,056: | Line 1,056: | ||
=={{header|R}}== |
=={{header|R}}== |
||
===Direct Summation=== |
|||
The talk page helpfully points out that we can be remarkably lazy here. |
The talk page helpfully points out that we can be remarkably lazy here. |
||
<lang R>HofN <- function(n) sum(1/seq_len(n)) #Task 1 |
<lang R>HofN <- function(n) sum(1/seq_len(n)) #Task 1 |
||
Line 1,068: | Line 1,069: | ||
> print(sapply(1:10, function(x) which.max(H > x))) #Task 3 and stretch |
> print(sapply(1:10, function(x) which.max(H > x))) #Task 3 and stretch |
||
[1] 2 4 11 31 83 227 616 1674 4550 12367</pre> |
[1] 2 4 11 31 83 227 616 1674 4550 12367</pre> |
||
===Cumulative Sums=== |
|||
As for doing this properly, R provides a handy cumsum function. |
|||
<lang R>firstNHarmonicNumbers <- function(n) cumsum(1/seq_len(n)) #Task 1 |
|||
H <- firstNHarmonicNumbers(100000) #Runs stunningly quick |
|||
print(H[1:20]) #Task 2 |
|||
print(sapply(1:10, function(x) which.max(H > x))) #Task 3 and stretch</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |