Somma parziale della sequenza armonica!


13

Definizione

In matematica, la sequenza armonica si riferisce a una sequenza in cui

Harmonic Sequence Equation

cioè il n esimo termine della sequenza uguale al reciproco del n .


introduzione

In questa sfida, dato un intero positivo n come input, emette la somma parziale dei primi n termini della sequenza armonica.


Ingresso

Ti verrà dato un numero intero positivo (all'interno dell'intervallo di numeri supportati dalla tua lingua). Può essere Signed e Unsigned (dipende da te), poiché la sfida richiede solo numeri interi positivi.

È possibile accettare l'input in qualsiasi modo, tranne supponendo che sia presente in una variabile predefinita. prompt()È consentita la lettura da file, terminale, finestra modale ( in JavaScript) ecc. È ammesso anche prendere l'input come argomento di funzione.


Produzione

Il programma dovrebbe generare la somma dei primi n termini della sequenza armonica come float (o intero se l'uscita è uniformemente divisibile per 1) con precisione di 5 cifre significative, dove n si riferisce all'input. Per trasmettere lo stesso nel gergo matematico, devi calcolare

Harmonic Sequence Partial Sum of first n terms

dove n si riferisce all'input.

È possibile eseguire l'output in qualsiasi modo tranne che scrivere l'output in una variabile. alert()È consentita la scrittura su schermo, terminale, file, finestra modale ( in JavaScript) ecc. returnÈ consentito anche l' output come valore della funzione .


Regole aggiuntive


Casi test

I casi di test presuppongono che l'input sia 1-indicizzato

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

Criterio vincente

Questo è , quindi vince il codice più corto in byte!


Potresti darci alcune prove?
user41805,

2
Quale precisione è richiesta? L'output esatto è generalmente possibile solo come una frazione, ma in molte lingue dovranno essere numeri separati per numeratore e denominatore. Possiamo produrre a) un float, b) una frazione o una coppia intera c)?
Level River St,

2
@Arjun La serie armonica cresce all'infinito, quindi sarà difficile raggiungere i 10 decimali man mano che il numero sale a migliaia e milioni. Preferirei cifre significative anziché cifre decimali e non vedo la necessità di essere così preciso. 5 cifre significative dovrebbero essere sufficienti. così 9.9999E10piuttosto che99999999999.9999999999
Level River St,

Possiamo andare oltre 5 cifre significative?
Erik the Outgolfer,

A proposito, è noto che la sequenza armonica non contiene numeri interi diversi da a_1 = 1. iniziale (Idea di prova che a_n non è un numero intero per n> 1: sia 2 ^ k la potenza maggiore di 2 non superiore n; quindi 2 ^ k divide il denominatore di a_n.)
Greg Martin,

Risposte:



9

Python 3, 27 byte

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

0-indicizzazione o 1-indicizzazione?
Arjun,

2
Viene generato RuntimeErrorquando si gestisce l'input maggiore del limite di ricorsione, 1000 per impostazione predefinita.
sagiksp,

puoi farlo sys.setrecursionlimit(473755252663)ma alla fine lo stack traboccerà abbastanza facilmente
cat

@Arjun è indicizzato 1
shooqie

8

JavaScript, 19 18 byte

1 byte salvato grazie a @RickHitchcock

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

Questo è 1-indicizzato.

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

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


Da quello che ho visto di altri post, puoi rimuovere f=dalla tua risposta per salvare 2 byte.
Rick Hitchcock,

1
@RickHitchcock Non riesco a rimuovere f=perché la funzione è ricorsiva e fa riferimento a se stessa f(--a). Ma se questa non fosse una soluzione ricorsiva, sarei stato in grado di farlo
user41805,

Ah, ha senso! Salva un byte con f=a=>a&&1/a+f(--a).
Rick Hitchcock,

@RickHitchcock Nice one!
user41805,

6

APL (Dyalog) , 5 byte

+/÷∘⍳

Provalo online!

È possibile aggiungere ⎕PP←{number}all'intestazione per modificare la precisione in {number}.

Questo è 1-indicizzato.

Spiegazione

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

6

Mathematica, 21 20 16 byte

Questa soluzione è 1 indicizzata.

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

È 1-indicizzazione
J42161217,

1
> Non è necessario utilizzare un built-in per calcolare la somma parziale dei primi n elementi. (Sì, è per te Mathematica!)
MCCCS,

4
OP significa che non posso usare HarmonicNumber [#] &
J42161217,

4
E si può accorciare ulteriormente Tr[1./Range@#]&.
Greg Martin,

2
@Ian Mathematica può visualizzare 5 sig fig, ma la funzione restituisce numeri di precisione della macchina (52 bit binari o poco meno di 16 cifre decimali di precisione)
LLlAMnYP




5

Japt -x, 8 6 5 3 bytes

õpJ

With some thanks to ETHproductions

Try it online


0-indexing or 1-indexing?
Arjun

I think you can save a byte with õ x@1/X
ETHproductions

...and another couple bytes by using XpJ instead of 1/X :-)
ETHproductions

Thanks, @ETHproductions :) I twigged those as soon as I walked away.
Shaggy

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

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

You can use W instead of -1.
Erik the Outgolfer

@EriktheOutgolfer has outgolfed himself :-)
Luis Mendo

@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

@Erik It was meant as a joke. Thanks for the help
Luis Mendo

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.



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.


Thanks @Christopher for the formatting. With that, the duplication of backslash was no longer necessary.
avl42

No problem! It looks better
Christopher


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

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


1

C, 54 bytes

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

Uses 1-indexed numbers.



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

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



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.


Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.