Partial Sum of Harmonic Sequence!

13

0

Definition

In Mathematics, Harmonic Sequence refers to a sequence where

Harmonic Sequence Equation

i.e. the nth term of the sequence equals the reciprocal of n.


Introduction

In this challenge, given a positive integer n as input, output the Partial Sum of first n terms of the Harmonic Sequence.


Input

You'll be given a positive integer (within the range of numbers supported by your language). It can be either of Signed and Unsigned (depends on you), since the challenge requires only positive integers.

You can take the input in any way except assuming it to be present in a predefined variable. Reading from file, terminal, modal window (prompt() in JavaScript) etc. is allowed. Taking the input as function argument is allowed as well.


Output

Your program should output the sum of the first n terms of the Harmonic Sequence as a float (or integer if the output is evenly divisible by 1) with precision of 5 significant figures, where n refers to the input. To convey the same in Mathematical jargon, you need to compute

Harmonic Sequence Partial Sum of first n terms

where n refers to the input.

You can output in any way except writing the output to a variable. Writing to screen, terminal, file, modal window (alert() in JavaScript) etc. is allowed. Outputting as function return value is allowed as well.


Additional Rules


Test Cases

The Test Cases assume the input to be 1-indexed

Input     Output
1         1
2         1.5
3         1.8333
4         2.0833
5         2.2833

Winning Criterion

This is , so the shortest code in bytes wins!

Arjun

Posted 2017-05-28T09:47:00.517

Reputation: 4 544

Could you give us some testcases? – user41805 – 2017-05-28T09:50:01.370

2What precision is required? Exact output is generally only possible as a fraction, but in many languages that will have to be separate numbers for numerator and denominator. Can we output a)a float, b)a fraction or integer pair c)either? – Level River St – 2017-05-28T09:52:51.840

2@Arjun The harmonic series grows to infinity so it will get hard to meet 10 decimal places as the number gets into the thousands and millions. I would go for significant figures rather than decimal places, and I see no need to be so precise. 5 significant figures should be enough. so 9.9999E10 rather than 99999999999.9999999999 – Level River St – 2017-05-28T10:17:04.193

Can we go over 5 significant figures? – Erik the Outgolfer – 2017-05-28T10:25:11.487

By the way, it's known that the harmonic sequence does not contain any integers other than the initial a_1 = 1. (Idea of proof that a_n is not an integer for n>1: let 2^k be the largest power of 2 not exceeding n; then 2^k divides the denominator of a_n.) – Greg Martin – 2017-05-28T19:53:42.453

Is it fine if the output is a fraction instead of a float? Clojure's default type in division is a ratio, which is basically a fraction. – clismique – 2017-06-01T10:47:15.723

@Qwerp-Derp No, sorry, that's not allowed. – Arjun – 2017-06-02T06:11:52.197

Answers

4

Jelly, 3 bytes

İ€S

Try it online!

1-indexed.

Explanation:

İ€S Main link, monadic
İ€         1 / each one of [1..n]
  S Sum of

Erik the Outgolfer

Posted 2017-05-28T09:47:00.517

Reputation: 38 134

9

Python 3, 27 bytes

h=lambda n:n and 1/n+h(n-1)

shooqie

Posted 2017-05-28T09:47:00.517

Reputation: 5 032

0-indexing or 1-indexing? – Arjun – 2017-05-28T11:29:58.113

2Throws RuntimeError when handling input greater than the recursion limit, 1000 by default. – sagiksp – 2017-05-28T15:04:09.647

you can do sys.setrecursionlimit(473755252663) but the stack will eventually overflow quite easily – cat – 2017-05-29T04:31:19.103

@Arjun it's 1-indexed – shooqie – 2017-05-29T20:23:33.687

8

JavaScript, 19 18 bytes

1 byte saved thanks to @RickHitchcock

f=a=>a&&1/a+f(--a)

This is 1-indexed.

f=a=>a&&1/a+f(--a)

for(i=0;++i<10;)console.log(f(i))

user41805

Posted 2017-05-28T09:47:00.517

Reputation: 16 320

From what I've seen of other posts, you can remove f= from your answer to save 2 bytes. – Rick Hitchcock – 2017-05-28T10:44:06.750

1@RickHitchcock I cannot remove f= because the function is recursive and it references itself in f(--a). But if this was not a recursive solution, I would have been able to do that – user41805 – 2017-05-28T10:45:30.543

Ah, makes sense! Save one byte with f=a=>a&&1/a+f(--a). – Rick Hitchcock – 2017-05-28T10:49:52.650

@RickHitchcock Nice one! – user41805 – 2017-05-28T10:52:13.197

6

Mathematica, 21 20 16 bytes

This solution is 1-indexed.

Sum[1./i,{i,#}]&

J42161217

Posted 2017-05-28T09:47:00.517

Reputation: 15 931

It is 1-indexing – J42161217 – 2017-05-28T11:31:07.683

1ockquote>

You must not use a built-in to calculate the partial sum of the first n elements. (Yeah, it's for you Mathematica!)

– MCCCS – 2017-05-28T11:32:46.500

4OP means I can't use HarmonicNumber[#] & – J42161217 – 2017-05-28T11:35:56.743

@Jenny_mathy True. – Arjun – 2017-05-28T11:44:53.973

Question only asked for 5 sig fig so you can shorten it to: Sum[1./i,{i,#}]& – Ian Miller – 2017-05-28T16:42:02.973

4And one can further shorten to Tr[1./Range@#]&. – Greg Martin – 2017-05-28T19:56:23.853

@Ian Miller If you see the edit you'll see that OP was asking for 10. Thanks for letting me know! and for -4 bytes – J42161217 – 2017-05-28T20:06:34.997

@Greg Martin nice approach! – J42161217 – 2017-05-28T20:20:58.823

@GregMartin come on, 1 more byte and this will be as short as the built-in :-) – LLlAMnYP – 2017-05-29T07:36:15.283

2@Ian Mathematica may display 5 sig fig, but the function returns machine-precision numbers (52 binary bits or just under 16 decimal digits of precision) – LLlAMnYP – 2017-05-30T09:12:56.873

6

APL (Dyalog), 5 bytes

+/÷∘⍳

Try it online!

You can add ⎕PP←{number} to the header to change the precision to {number}.

This is 1-indexed.

Explanation

+/÷∘⍳                     Right argument; n
    ⍳                     Range; 1 2 ... n
  ÷                       Reciprocal; 1/1 1/2 ... 1/n
+/                        Sum; 1/1 + 1/2 + ... + 1/n

user41805

Posted 2017-05-28T09:47:00.517

Reputation: 16 320

5

Pari/GP, 18 bytes

n->sum(i=1,n,1./i)

1-indexing.

Try it online!

alephalpha

Posted 2017-05-28T09:47:00.517

Reputation: 23 988

5

CJam, 11 bytes

1.ri,:)f/:+

Try it online!

1-indexed.

Erik the Outgolfer

Posted 2017-05-28T09:47:00.517

Reputation: 38 134

5

PHP, 33 Bytes

1-indexing

for(;$i++<$argn;)$s+=1/$i;echo$s;

Try it online!

Jörg Hülsermann

Posted 2017-05-28T09:47:00.517

Reputation: 13 026

5

Japt -x, 8 6 5 3 bytes

õpJ

With some thanks to ETHproductions

Try it online

Shaggy

Posted 2017-05-28T09:47:00.517

Reputation: 24 623

0-indexing or 1-indexing? – Arjun – 2017-05-28T11:27:18.127

I think you can save a byte with õ x@1/X – ETHproductions – 2017-05-28T12:25:57.740

...and another couple bytes by using XpJ instead of 1/X :-) – ETHproductions – 2017-05-28T12:27:04.247

Thanks, @ETHproductions :) I twigged those as soon as I walked away. – Shaggy – 2017-05-28T12:45:38.697

Actually I don't think you even need the _ due to auto-functions. I should really write that tip :P (I should have time today or tomorrow, due to it being Memorial Day) – ETHproductions – 2017-05-28T14:50:18.837

Nice one, @ETHproductions. – Shaggy – 2017-05-28T14:59:17.090

4

CJam, 11 10 bytes

1 byte removed thanks to Erik the outgolfer

ri),{W#+}*

This uses 1-based indexing.

Try it online!

Explanation

ri            e# Read integer, n
  )           e# Increment by 1: gives n+1
   ,          e# Range: gives [0 1 2 ... n]
    {   }*    e# Fold this block over the array
     W#       e# Inverse of a number
       +      e# Add two numbers

Luis Mendo

Posted 2017-05-28T09:47:00.517

Reputation: 87 464

You can use W instead of -1. – Erik the Outgolfer – 2017-05-28T12:24:44.627

@EriktheOutgolfer has outgolfed himself :-) – Luis Mendo – 2017-05-28T13:04:00.383

@LuisMendo I like my name, it's just a name. And yes I outgolfed myself in the process of helping a fellow golfer golf even further. – Erik the Outgolfer – 2017-05-28T13:10:24.667

@Erik It was meant as a joke. Thanks for the help – Luis Mendo – 2017-05-28T13:57:40.373

3

05AB1E, 3 bytes

LzO

Try it online!

1-indexed.

Erik the Outgolfer

Posted 2017-05-28T09:47:00.517

Reputation: 38 134

3

Haskell, 20 bytes

f 0=0
f n=1/n+f(n-1)

Original solution, 22 bytes

f n=sum[1/k|k<-[1..n]]

These solutios assumes 1-indexed input.

Ryan McCleary

Posted 2017-05-28T09:47:00.517

Reputation: 61

3

R, 15 bytes

sum(1/1:scan())

Try it online!

Nitrodon

Posted 2017-05-28T09:47:00.517

Reputation: 9 181

3

Tcl 38 bytes

proc h x {expr $x?1./($x)+\[h $x-1]:0}

That's a very dirty hack, and the recursive calls pass literal strings like "5-1-1-1..." until it evaluates to 0.

avl42

Posted 2017-05-28T09:47:00.517

Reputation: 111

Thanks @Christopher for the formatting. With that, the duplication of backslash was no longer necessary. – avl42 – 2017-05-28T20:30:12.373

No problem! It looks better – Christopher – 2017-05-28T21:30:10.710

2

Pyth, 5 bytes

scL1S

Try it here.

1-indexed.

Erik the Outgolfer

Posted 2017-05-28T09:47:00.517

Reputation: 38 134

2

Axiom, 45 34 bytes

f(x:PI):Any==sum(1./n,n=1..x)::Any

1-Indexed; It has argument one positive integer(PI) and return "Any" that the sys convert (or not convert) to the type useful for next function arg (at last it seems so seeing below examples)

(25) -> [[i,f(i)] for i in 1..9]
   (25)
   [[1,1.0], [2,1.5], [3,1.8333333333 333333333], [4,2.0833333333 333333333],
    [5,2.2833333333 333333333], [6,2.45], [7,2.5928571428 571428572],
    [8,2.7178571428 571428572], [9,2.8289682539 682539683]]
                                                      Type: List List Any
(26) -> f(3000)
   (26)  8.5837498899 591871142
                                        Type: Union(Expression Float,...)
(27) -> f(300000)
   (27)  13.1887550852 056117
                                        Type: Union(Expression Float,...)
(29) -> f(45)^2
   (29)  19.3155689383 88117644
                                                   Type: Expression Float

RosLuP

Posted 2017-05-28T09:47:00.517

Reputation: 3 036

2

MATL, 5 bytes

:l_^s

This solution uses 1-based indexing.

Try it at MATL Online

Explanation

    % Implicitly grab input (N)
:   % Create an array from [1...N]
l_^ % Raise all elements to the -1 power (take the inverse of each)
s   % Sum all values in the array and implicitly display the result

Suever

Posted 2017-05-28T09:47:00.517

Reputation: 10 257

1

C, 54 bytes

i;float f(n){float s;for(i=n+1;--i;s+=1./i);return s;}

Uses 1-indexed numbers.

Uriel

Posted 2017-05-28T09:47:00.517

Reputation: 11 708

1

Brachylog, 6 bytes

⟦₁/₁ᵐ+

Try it online!

This is 1-indexed.

Explanation

⟦₁         Range [1, …, Input]
    ᵐ      Map:
  /₁         Inverse
     +     Sum

Fatalize

Posted 2017-05-28T09:47:00.517

Reputation: 32 976

1

QBIC, 13 bytes

[:|c=c+1/a]?c

Explanation

[ |        FOR a = 1 to
 :            the input n
   c=c+    Add to c (starts off as 0)
   1/a     the reciprocal of the loop iterator
]          NEXT
?c         PRINT c

steenbergh

Posted 2017-05-28T09:47:00.517

Reputation: 7 772

1

Gol><>, 8 bytes

F1LP,+|B

Try it online!

Example full program & How it works

1AGIE;GN
F1LP,+|B

1AGIE;GN
1AG       Register row 1 as function G
   IE;    Take input as int, halt if EOF
      GN  Call G and print the result as number
          Repeat indefinitely

F1LP,+|B
F     |   Repeat n times...
 1LP,       Compute 1 / (loop counter + 1)
     +      Add
       B  Return

Bubbler

Posted 2017-05-28T09:47:00.517

Reputation: 16 616

0

Tcl, 61 bytes

proc h {x s\ 0} {time {set s [expr $s+1./[incr i]]} $x;set s}

Try it online!

sergiol

Posted 2017-05-28T09:47:00.517

Reputation: 3 055

0

Haskell, 21 bytes

f n=sum$map(1/)[1..n]

Uri Goren

Posted 2017-05-28T09:47:00.517

Reputation: 101

0

C (gcc), 35 bytes

float f(n){return n?1./n+f(--n):0;}

Try it online!

Giacomo Garabello

Posted 2017-05-28T09:47:00.517

Reputation: 1 419

0

Braingolf, 20 bytes [non-competing]

VR1-1[1,!/M,$_1+]v&+

This won't actually work due to braingolf's inability to work with floats, however the logic is correct.

Explanation:

VR1-1[1,!/M,$_1+]v&+   Implicit input
VR                     Create new stack and return to main stack
  1-                   Decrement input
    1                  Push 1
     [..........]      Loop, always runs once, then decrements first item on stack at ]
                       Breaks out of loop if first item on stack reaches 0
      1,!/             Push 1, swap last 2 values, and divide without popping
                       Original values are kept on stack, and result of division is pushed
          M,$_         Move result of division to next stack, then swap last 2 items and
                       Silently pop last item (1)
              1+       Increment last item on stack
                 v&+   Move to next stack, sum entire stack 
                       Implicit output of last item on current stack

Here's a modified interpreter that supports floats. First argument is input.

Skidsdev

Posted 2017-05-28T09:47:00.517

Reputation: 9 656