title: Find separating sets

text:
# Question
Title: Find separating sets
Two points `p`and `q` in a topological space can be separated if there are open sets `U` and `V` such that:

1. `p` is an element of `U` and `q` is an element of `V`
2. `U` and `V` do not have any elements in common

Your task is given a topology (a set of open sets) and two points `p` and `q` (`p!=q`) to output sets `U` and `V` satisfying the above conditions, or decide that such sets do not exist.

## Examples:

```
{{},{0},{1},{0,1}} 0 1                             -> {0},{1}
{{},{0},{1,2},{0,1,2}} 0 1                         -> {0},{1,2}
{{},{0,1},{2,3},{2,3,4},{0,1,2,3},{0,1,2,3,4}} 1 2 -> {0,1},{2,3} or {0,1},{2,3,4}
{{},{1,2},{3,4},{5,6},{1,2,3,4},{1,2,5,6},{3,4,5,6},{1,2,3,4,5,6}} 1 3 -> {1,2},{3,4} or {1,2},{3,4,5,6} or {1,2,5,6},{3,4}
{{},{1,2},{3,4},{5,6},{1,2,3,4},{1,2,5,6},{3,4,5,6},{1,2,3,4,5,6}} 1 5 -> {1,2},{5,6} or {1,2,3,4},{5,6} or {1,2},{3,4,5,6}

{{},{0,1}} 0 1                                     -> "not separable"
{{},{1},{1,2}} 1 2                                 -> "not seperable"
{{},{1,2,3},{1,3},{2,3},{3}} 1 2                   -> "not seperable"
{{},{0},{1,2},{0,1,2}} 1 2                         -> "not separable"
{{},{1,2},{3,4},{5,6},{1,2,3,4},{1,2,5,6},{3,4,5,6},{1,2,3,4,5,6}} 1 2 -> "not separable"

```

## Rules:

* You can assume the the Input is valid (a set of sets, that defines a Topology1)
* You may assume that the two given points are different and contained in at least one of the sets in the Topology
* You may use lists instead of sets for input/output
* If you use lists you can assume that the elements are unique and sorted in any convenient order
* If there are multiple possibilities to separate the elements you may return any **one** of them
* Outputting the complete list of all matches is **not** allowed
* If the two points cannot be separated, you may output any value, as long as it cannot be mistaken for the output in a separable case
* It is allowed to throw an exception to indicate the non-separable case
* Your code should be able to handle sets with at least 31 distinct elements
* This is the shortest solution (per language) wins

---

1 *A set S of sets is a topology if:*

*- It contains the empty set and the set of all elements
- Any (finite) intersection of elements in S is an element of S*2. *Any union of elements in S is an element of S*

# Answer
# Python, 63 bytes

```
lambda l,*I:(O:=[min(l,key={c}.__xor__)for c in I])[0]&O[1]or O

```

Attempt This Online!

This expects a list of sets for the topology. The list shall be ordered by descending length as allowed per OP. (Actually, it suffices that the longest set comes first.)

## How?

This depends on the specific implementation of `min`. It assumes that `min` works left to right and updates the current minimum whenever the next element is smaller than it. In particular, elements that cannot be compared to the current minimum are ignored. We use this to have `min` ignore exactly the subsets that contain `c` by starting off with the full set minus `c`. As this is the opposite of what we actually need we `key` `min` with `^{c}`, so we can start with the full set and ignore all subsets *not* containing `c`.

Other than that it works like the other versions.

# Python, 65 bytes

```
lambda l,*I:(O:=[min(l&{x|{c}for x in l})for c in I])[0]&O[1]or O

```

Attempt This Online!

This takes a set of frozensets for the topology.

# Python, 66 bytes

```
lambda l,*I:(O:=[min(x for x in l if{c}&x)for c in I])[0]&O[1]or O

```

Attempt This Online!

Returns a disjoint pair of sets containing either point. Or a single set in case of failure.

Test harness stolen from @solid.py.

## How?

Being a finite topology `l` contains the intersections of all sets containing `p=I[0]` and of all sets containing `q=I[1]`. We need only check these. To obtain the intersections we use the fact that they are minimal within the subset of subsets containing `p` (or `q`). Note that it does not matter that typically some subsets will not be comparable (both `<` and `>=` return `False`). For the `min` function to succeed it suffices that there is a minimum, i.e. one element that is comparable to and smaller than all the others.
> 7 votes

# Answer
# , ~~60~~ 75 bytes

*Edit: +15 bytes to fix bug*

```
\(t,p,q){for(i in t)for(j in t)if(p%in%i&q%in%j&!any(i%in%j))F=list(i,j);F}

```

Attempt This Online!

Outputs a list of two separating sets, or `FALSE` if no separating sets can be found.
> 5 votes

# Answer
# Python, 64 bytes

-8 bytes, -3 bytes and -2 bytes thanks to `Value Ink`, `loopy walt` and `xnor` respectively. Also, thanks to `Neil` and `bsoelch` for their suggestions.

Takes as input a list of sets, and returns a pair (tuples) of separated sets. In the `not separable` case it raises an exception.

```
lambda l,p,q:[(u,v)for u in l for v in l if{p}-u=={q}-v==u&v][0]

```

Attempt This Online!
> 5 votes

# Answer
# 05AB1E, ~~16~~ ~~15~~ 13 bytes

```
ãʒ`åyIδå«˜J₄-

```

Inputs in the order \\$topology, \[p,q\]\\$. Outputs all possible results, so an empty list for 'not separable'. (Although all given test cases have \\$p\<q\\$, it'll also work if \\$p\>q\\$.)

Try it online or verify all test cases.

**Explanation:**

```
ã         # Cartesian power of 2 to create all pairs of the first (implicit) input-list
          # of lists (including pairs of the same topology-sets)
 ʒ        # Filter this list of pairs of lists by:
  `å      #  Verify (the inverse of) rule 2:
  `       #   Pop and push both lists separated to the stack
   å      #   Check for each value in the second list whether it's in the first list
  yIδå    #  Verify (a portion of) rule 1:
  y       #   Push the current pair of lists again
   I      #   Push the second input-pair of integers
    δ     #   Pop both, and apply double-vectorized:
     å    #    Contains-check
  «˜J₄-   #  Combine the checks of the two rules:
  «       #   Merge the two lists together
   ˜J     #   Flatten and join it to a string
     ₄-   #   Subtract 1000, to verify whether the string is of the form "0...01001",
          #   where "0...0" comes from the check of rule 2
          #   and "1001" from the check of rule 1
          #   (only 1 is truthy in 05AB1E)
          # (after which the filtered list is output implicitly)

```
> 4 votes

# Answer
# Ruby, 50 bytes

Returns `nil` if no pair exists.

```
->s,x,*y{s.product(s).find{[x]-_1|y-_2|_1&_2==[]}}

```

Attempt This Online!

```
->s,x,*y{                               # Anonymous lambda that takes three arguments
                                        #  (y is splatted to make it a one-element array)
         s.product(s)                   # Cartesian product of the topology against itself
          .find{                        # Find first pair that matches the following
                [x]-_1                  # Subtract elements of U (_1) from an array w/ only x
                                        #  (empty array if x is in U)
                      |y-_2             # intersect w/ subtraction of V (_2) from y
                                        #  (empty if y is in V)
                           |_1&_2       # intersect w/ union of U and V (empty if no overlap)
                                 ==[]   # If the intersection of these three is an empty array,
                                        #  the conditions have been met
                                     }  # End find call
                                      } # End lambda definition

```
> 4 votes

# Answer
# JavaScript (ES6), 79 bytes

*-6 thanks to @l4m2*

Expects `(a,p,q)` where `a` is a list of sets.

Returns either a pair of sets or `[ undefined, undefined ]`.

```
(a,p,q)=>[a.find(U=>b=a.find(V=>U.has(p)&V.has(q)>[...V].some(v=>U.has(v)))),b]

```

Try it online!

Patiently waiting for new ECMAScript set methods ...

### Commented

```
(a, p, q) => [         // a[] = list of sets, (p, q) = integers
  a.find(U =>          // look for some set U in a[]:
    b = a.find(V =>    //   and some other set V in a[], saved in b:
      U.has(p) &       //     such that p belongs to U,
      V.has(q) >       //     q belongs to V,
      [...V].some(v => //     and there's not any value v from V ...
        U.has(v)       //       ... that also belongs to U
      )                //     end of some()
    )                  //   end of inner find()
  ),                   // end of outer find()
  b                    // output the 2nd set
]                      // (if the 1st set is undefined, so is b)

```
> 2 votes

# Answer
# Pyth, 13 bytes

```
f!+@FTs-VvzT*

```

Attempt This Online!

Returns a list of all possible separating pairs, `[]` if none exist.

### Explanation

```
f!+@FTs-VvzT*QQ    # implicitly add QQ
                   # implicitly assign Q=eval(input()) z=input()
            *QQ    # cartesian product of Q and Q
f                  # filter on lambda T
       -VvzT       #   vectorize subtraction on eval(z) and T
      s            #   sum (empty set for valid pairs)
   @FT             #   fold T on intersection
  +                #   add (empty set for valid pairs)
 !                 #   not (true for empty set)

```
> 2 votes

# Answer
# Retina, 99 bytes

```
~L$`(.)¶(.)$
,-5G`¶O$$`.$*($2).$*|.+¶$$1¶Lw$$m`^(.$*$1.$*)$$[\S\s]+^(.$*$2.$*)$$¶$$1,$$2¶A`(.).$*\1

```

Try it online! Uses strings as sets. Takes input on separate lines but test suite splits on commas for convenience. Outputs all possible results. Explanation: The program itself is only one stage, but works by generating a program to do the actual work and then using the `~` flag to run the resulting program. As an example, it generates the following code for the last test case:

```
,-5G`

```

Delete the two points leaving just the sets.

```
O$`.*(2).*|.+
$1

```

Sort the sets containing the second point to the end.

```
Lw$m`^(.*1.*)$[\S\s]+^(.*2.*)$
$1,$2

```

List most pairs of sets where the first set contains the first point and the second set contains the second point. (Some pairs where the first set contains both points are missed but they're not relevant anyway.)

```
A`(.).*\1

```

Delete pairs that have an element in common.
> 2 votes

# Answer
# Factor \+ `combinators.extras sets.extras`, 77 bytes

Returns the first two separating sets found, or two `f`.

```
[| s x y | s s [| a b | a b disjoint? x a in? y b in? 3and ] cartesian-find ]

```

Attempt This Online!

* `[| s x y | ... ]` A quotation (anonymous function) taking named inputs s (for the sets), x, and y.
* `s s [| a b | ... ] cartesian-find` Find the first pair in `s` that is true when `...` is run on it. Name the inputs (the two sets) to the quotation `a` and `b`.
* `a b disjoint?` Is the intersection of `a` and `b` empty? (Leaves a boolean on the stack.)
* `x a in?` Is `x` in `a`? (Leaves a boolean on the stack.)
* `y b in?` Is `y` in `b`? (Leaves a boolean on the stack.)
* `3and` Take the logical and of three objects.
> 2 votes

# Answer
# Jelly, 10 bytes

```
fƇⱮf/€Ṇf/¡

```

A dyadic Link that accepts the topology as a list of lists\* on the left and the points as a list on the right and yields the smallest cardinality separating sets or `0` if no separating set is possible.

* Jelly has no sets.

**Try it online!** Or see the test-suite.

### How?

```
fƇⱮf/€Ṇf/¡ - Link: Topology; Points
  Ɱ        - map across {Points} with:
 Ƈ         -   keep those Sets of {Topology} for which:
f          -     {Set} filter keep {Point}
     €     - for each of these two FilteredTopolgies:
    /      -   reduce by:
   f       -     filter keep
                   -> Intersection of the FilteredTopology
         ¡ - repeat...
        /  - ...times: reduce {Intersections} by:
       f   -             filter keep
                           N.B. [] is falsey so repeat zero times
                                other lists are truthy so repeat once
      Ṇ    - ...action: logical NOT

```
> 2 votes

# Answer
# Haskell, ~~89~~ 88 bytes

```
f t p q=head[x|x@[u,v]<-t#t,p%u&&q%v&&all(\[i,j]->i/=j)(u#v)];s#t=sequence[s,t];(%)=elem

```

Attempt This Online!

Note that `head` is redefined for testing purposes only. If you remove the header, function `f` returns the two open sets if they exists, otherwise throws the exception `*** Exception: Prelude.head: empty list`.
> 2 votes

# Answer
# Charcoal, 23 bytes

```
ＦθＥΦθ∧№ιη∧№κζ⁼ι⁻ικ⭆¹⟦ικ

```

Try it online! Link is to verbose version of code. Uses lists as sets. Outputs all possible results. Explanation:

```
 θ                      List of lists
Ｆ                       Loop over elements
    θ                   List of lists
   Φ                    Filtered where
       ι                Outer list
      №                 Contains
        η               First point
     ∧                  Logical And
           κ            Inner list
          №             Contains
            ζ           Second point
         ∧              Logical And
              ι         First list
             ⁼          Equals
                ι       First list
               ⁻        Removing elements in
                 κ      Second list
  Ｅ                     Map over results
                  ⭆¹⟦ικ Pretty-print both lists

```
> 1 votes

# Answer
# Scala 3, 89 bytes

```
(l,p,q)=>for{u<-l;v<-l;if u.contains(p)&&v.contains(q)&&u.intersect(v).isEmpty}yield(u,v)

```

Attempt This Online!
> 1 votes

# Answer
# Arturo, 65 bytes

```
$[s m n][loop s'a->loop s'b->if∧∧a<>a--m b<>b--n a=a--b[a b]]

```

Try it!

Returns every valid pair.

```
$[s m n][           ; a function taking three arguments (s is sets)
    loop s'a->      ; loop over s, assign current elt to a
        loop s'b->  ; loop over s, assign current elt to b
            if∧∧    ; if the following 3 statements are true...
            a<>a--m ; m is in a
            b<>b--n ; n is in b
            a=a--b  ; a intersect b is empty
            [a b]   ; then return a and b
]                   ; end function

```
> 0 votes

# Answer
# Perl 5, 86 bytes

```
sub{($s,$p,$q)=@_;map{$u=$_;map[$u,$_],grep$p~~@$u&$q~~@$_&!(grep$_~~@$u,@$_),@$s}@$s}

```

Try it online!
> 0 votes

---
Tags: code-golf, math, topology
---


title: Partial Sum of Harmonic Sequence!

text:
# Question
Title: Partial Sum of Harmonic Sequence!
# Definition

> In Mathematics, **Harmonic Sequence** refers to a sequence where
>
> $$a\_n = \frac 1 n$$
>
> i.e. the \\$n\_{th}\\$ 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

$$\sum\_{i=1}^n \frac 1 i$$

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!

# Answer
> 4 votes
# Jelly, 3 bytes

```
İ€S

```

Try it online!

1-indexed.

Explanation:

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

```

# Answer
> 9 votes
# Python 3, 27 bytes

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

```

# Answer
> 8 votes
# 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))
```

# Answer
> 6 votes
# Mathematica, ~~21~~ ~~20~~ 16 bytes

This solution is 1-indexed.

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

```

# Answer
> 6 votes
# 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

```

# Answer
> 5 votes
# Pari/GP, 18 bytes

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

```

1-indexing.

Try it online!

# Answer
> 5 votes
# CJam, 11 bytes

```
1.ri,:)f/:+

```

Try it online!

1-indexed.

# Answer
> 5 votes
# PHP, 33 Bytes

1-indexing

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

```

Try it online!

# Answer
> 5 votes
# Japt `-x`, ~~8~~ ~~6~~ ~~5~~ 3 bytes

```
õpJ

```

With some thanks to ETHproductions

Try it online

# Answer
> 4 votes
# 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

```

# Answer
> 3 votes
# 05AB1E, 3 bytes

```
LzO

```

Try it online!

1-indexed.

# Answer
> 3 votes
## 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.

# Answer
> 3 votes
# , 15 bytes

```
sum(1/1:scan())

```

Try it online!

# Answer
> 3 votes
## 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.

# Answer
> 2 votes
# Pyth, 5 bytes

```
scL1S

```

Try it here.

1-indexed.

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
# Husk, 3 bytes

```
ṁ\ḣ

```

Try it online!

Output is a fraction.

# Answer
> 2 votes
# Vyxal, 3 bytes

```
ɾĖ∑

```

Lame answer, but range -\> reciprocal -\> sum -\> implicit out, same as jelly

Try it Online!

# Vyxal `s`, 2 bytes

```
ɾĖ

```

2 Bytes w/ -s from @lyxal, -s sums the stack

Try it Online!

# Answer
> 1 votes
# C, 54 bytes

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

```

Uses 1-indexed numbers.

# Answer
> 1 votes
## Haskell, 21 bytes

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

```

# Answer
> 1 votes
# Brachylog, 6 bytes

```
⟦₁/₁ᵐ+

```

Try it online!

This is 1-indexed.

### Explanation

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

```

# Answer
> 1 votes
## 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

```

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# Rust, 36 bytes

```
|n|(1..=n).map(|n|1./n as f64).sum()

```

Try it online!

Input is an integer, if the input is \<=0 the output is zero, and inputting one gets one.

# Answer
> 1 votes
# , 9 bytes

```
1#.1%1+i.

```

I'm only posting this because I think it looks really pretty.

Attempt This Online!

```
1#.1%1+i.
       i.  NB. range 0..n-1
     1+    NB. add 1
   1%      NB. 1 divided by each element
1#.        NB. sum the result

```

# Answer
> 1 votes
# Pyt, 3 bytes

```
ř⅟Ʃ
        implicit input
ř       produces a list containing 1 to n
 ⅟      takes the reciprocals
  Ʃ     sums the list
        (implicit print)

```

Try it online!

# Answer
> 1 votes
# Scala, 47 bytes

Try it online!

```
def h(n:Int):Double=if(n==0)0 else 1.0/n+h(n-1)

```

# Answer
> 1 votes
# Thunno 2 `S`, 2 bytes

```
RỊ

```

Try it online!

#### Explanation

```
RỊ  # Implicit input
R   # One range
 Ị  # Reciprocal
    # Take the sum
    # Implicit output

```

# Answer
> 0 votes
# Tcl, 61 bytes

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

```

Try it online!

# Answer
> 0 votes
# C (gcc), 35 bytes

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

```

Try it online!

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# GolfScript, 17 bytes

```
~),{2.-1??./\/+}*

```

Try it online!

1-indexed

```
~                   # Parse n to an integer
 ),                 # Make an array from 0 to n
   {           }*   # For each number in the array, skipping the 0
    2.-1??          # 2^(2^-1) = sqrt( 2 )  We just need any float
          ./        # Divide previous number by itself, this will result in the float 1.0
            \/      # Divide 1.0 by the current number of the array
              +     # Add the result

```

Without the convertion to float it could be reduced to 10 bytes, but the output would be a fraction.

```
~),{-1?+}*

```

Try it online!

# Answer
> 0 votes
# Pip, 6 bytes

```
$+/\,a

```

Try it online!

### Explanation

```
     a  First command-line argument
   \,   Inclusive range from 1 through that number
  /     Invert each number in the range
$+      Fold on + (summing the list)
        Autoprint (implicit)

```

# Answer
> 0 votes
# Ly, ~~14~~ 12 bytes

```
n[:1f/f1-]&+

```

Try it online!

Found a simpler way to do this... The original was: `0ns[1f/+l1-s]p`

And here's what it's doing.

```
n

```

Get 'n' from the challenge (the number of iterations) from the input and push onto the stack.

```
[...]

```

As long as the top of the stack is non-zero.

```
:1f/

```

Duplicate the top of the stack (the iteration counter), and compute `1/n`.

```
f1-

```

Flip the two entries on the stack so that the `1/n` calculation is second and the iteration counter is on the top. Then decrement the iteration counter.

```
&+

```

Once all the values have been computed, sum the stack and print.

# Answer
> 0 votes
# Excel (2016), 28 bytes

```
=SUM(1/ROW(OFFSET(A1,,,A1)))

```

## Excel (current), 20 bytes

```
=SUM(1/SEQUENCE(A1))

```

# Answer
> 0 votes
# Desmos, 16 bytes

```
total(1/[1...n])

```

Try it on desmos!

Uses the total function instead of sigma notation to be able to shave off the latex. Also uses desmos's built-in vectorization.

# Answer
> 0 votes
# HP 28S, 18 bytes

```
0 1 ROT FOR K K INV + NEXT

```

# Answer
> 0 votes
# Raku, 15 bytes

```
{sum 1 X/1..$_}

```

Try it online!

`1 X/ 1..$_` is 1 cross-divided by the numbers from 1 up to the input number $\_, producing the list 1, 1/2, 1/3, ..., 1/$\_. Then (of course) `sum` sums them.

# Answer
> 0 votes
# J-uby, 16 bytes

```
:+|:sum+(:/&1.0)

```

Attempt This Online!

# Answer
> 0 votes
# \>\<\>, 17 bytes

```
0$:@?!n$:1-}1$,+!

```

Try it online!

# Answer
> 0 votes
# Itr, 4 bytes

`#¹¯S`

outputs result as fraction

online interpreter

append `0e*` for floating point output

## Explanation

```
#    ; read number from stdin
 ¹   ; 1-based range
  ¯  ; replace elements with their reciprocals
   S ; sum
     ; implicit output

```

---
Tags: code-golf, math, sequence
---


# Question
Title: Calculate the sum of the first n prime numbers
I'm surprised that this challenge isn't already here, as it's so obvious. (Or I'm surprised I couldn't find it and anybody will mark it as a duplicate.)

## Task

Given a non-negative integer \\$n\\$, calculate the sum of the first \\$n\\$ primes and output it.

## Example #1

For \\$n = 5\\$, the first five primes are:

* 2
* 3
* 5
* 7
* 11

The sum of these numbers is \\$2 + 3 + 5 + 7 + 11 = 28\\$, so the program has to output \\$28\\$.

## Example #2

For \\$n = 0\\$, the "first zero" primes are none. And the sum of no numbers is - of course - \\$0\\$.

## Rules

* You may use built-ins, e.g., to check if a number is prime.
* This is , so the lowest number of bytes in each language wins!

# Answer
> 15 votes
# 6502 machine code routine, 75 bytes

```
A0 01 84 FD 88 84 FE C4 02 F0 32 E6 FD A0 00 A5 FD C9 04 90 1F 85 64 B1 FB 85
65 A9 00 A2 08 06 64 2A C5 65 90 02 E5 65 CA D0 F4 C9 00 F0 DC C8 C4 FE D0 DB
A5 FD A4 FE 91 FB C8 D0 C8 A9 00 18 A8 C4 FE F0 05 71 FB C8 D0 F7 60

```

Expects a pointer to some temporary storage in `$fb`/`$fc` and the number of primes to sum up in `$2`. Returns the sum in `A` (the accu register).

Never did some prime checks in 6502 machine code, so here it finally comes ;)

Note this starts giving wrong results for inputs \>= 14. This is because of overflow, the code works with the "natural" number range of the 8bit platform which is `0 - 255` for *unsigned*.

### Commented disassembly

```
; function to sum the first n primes
;
; input:
;   $fb/$fc: pointer to a buffer for temporary storage of primes
;   $2:      number of primes to sum (n)
; output:
;   A:       sum of the first n primes
; clobbers:
;   $fd:     current number under primality test
;   $fe:     number of primes currently found
;   $64:     temporary numerator for modulo check
;   $65:     temporary divisor for modulo check
;   X, Y
 .primesum:
A0 01       LDY #$01            ; init variable for ...
84 FD       STY $FD             ; next prime number to test
88          DEY                 ; init number of found primes
 .mainloop:
84 FE       STY $FE             ; store current number of found primes
C4 02       CPY $02             ; compare with requested number
F0 32       BEQ .sum            ; enough primes -> calculate their sum
 .mainnext:
E6 FD       INC $FD             ; check next prime number
A0 00       LDY #$00            ; start check against first prime number
 .primecheckloop:
A5 FD       LDA $FD             ; load current number to check
C9 04       CMP #$04            ; smaller than 4?
90 1F       BCC .isprime        ; is a prime (shortcut to get list started)
85 64       STA $64             ; store to temp as numerator
B1 FB       LDA ($FB),Y         ; load from prime number table
85 65       STA $65             ; store to temp as divisor
A9 00       LDA #$00            ; init modulo to 0
A2 08       LDX #$08            ; iterate over 8 bits
 .bitloop:
06 64       ASL $64             ; shift left numerator
2A          ROL A               ; shift carry into modulo
C5 65       CMP $65             ; compare with divisor
90 02       BCC .bitnext        ; smaller -> to next bit
E5 65       SBC $65             ; otherwise subtract divisor
 .bitnext:
CA          DEX                 ; next bit
D0 F4       BNE .bitloop
C9 00       CMP #$00            ; compare modulo with 0
F0 DC       BEQ .mainnext       ; equal? -> no prime number
C8          INY                 ; next index in prime number table
C4 FE       CPY $FE             ; checked against all prime numbers?
D0 DB       BNE .primecheckloop ; no -> check next
 .isprime:
A5 FD       LDA $FD             ; prime found
A4 FE       LDY $FE             ; then store in table
91 FB       STA ($FB),Y
C8          INY                 ; increment number of primes found
D0 C8       BNE .mainloop       ; and repeat whole process
 .sum:
A9 00       LDA #$00            ; initialize sum to 0
18          CLC
A8          TAY                 ; start adding table from position 0
 .sumloop:
C4 FE       CPY $FE             ; whole table added?
F0 05       BEQ .done           ; yes -> we're done
71 FB       ADC ($FB),Y         ; add current entry
C8          INY                 ; increment index
D0 F7       BNE .sumloop        ; and repeat
 .done:
60          RTS

```

---

### Example C64 assembler program using the routine:

**Online demo**

**Code in ca65 syntax:**

```
.import primesum   ; link with routine above

.segment "BHDR" ; BASIC header
                .word   $0801           ; load address
                .word   $080b           ; pointer next BASIC line
                .word   2018            ; line number
                .byte   $9e             ; BASIC token "SYS"
                .byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes

.bss
linebuf:        .res    4               ; maximum length of a valid unsigned
                                        ; 8-bit number input
convbuf:        .res    3               ; 3 BCD digits for unsigned 8-bit
                                        ; number conversion
primebuf:       .res    $100            ; buffer for primesum function

.data
prompt:         .byte   "> ", $0
errmsg:         .byte   "Error parsing number, try again.", $d, $0

.code
                lda     #$17            ; set upper/lower mode
                sta     $d018

input:
                lda     #<prompt        ; display prompt
                ldy     #>prompt
                jsr     $ab1e

                lda     #<linebuf       ; read string into buffer
                ldy     #>linebuf
                ldx     #4
                jsr     readline

                lda     linebuf         ; empty line?
                beq     input           ; try again

                lda     #<linebuf       ; convert input to int8
                ldy     #>linebuf
                jsr     touint8
                bcc     numok           ; successful -> start processing
                lda     #<errmsg        ; else show error message and repeat
                ldy     #>errmsg
                jsr     $ab1e
                bcs     input

numok:
                sta     $2
                lda     #<primebuf
                sta     $fb
                lda     #>primebuf
                sta     $fc
                jsr     primesum        ; call function to sum primes
                tax                     ; and ...
                lda     #$0             ;
                jmp     $bdcd           ; .. print result

; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in A/Y, buffer length in X
.proc readline
                dex
                stx     $fb
                sta     $fc
                sty     $fd
                ldy     #$0
                sty     $cc             ; enable cursor blinking
                sty     $fe             ; temporary for loop variable
getkey:         jsr     $f142           ; get character from keyboard
                beq     getkey
                sta     $2              ; save to temporary
                and     #$7f
                cmp     #$20            ; check for control character
                bcs     checkout        ; no -> check buffer size
                cmp     #$d             ; was it enter/return?
                beq     prepout         ; -> normal flow
                cmp     #$14            ; was it backspace/delete?
                bne     getkey          ; if not, get next char
                lda     $fe             ; check current index
                beq     getkey          ; zero -> backspace not possible
                bne     prepout         ; skip checking buffer size for bs
checkout:       lda     $fe             ; buffer index
                cmp     $fb             ; check against buffer size
                beq     getkey          ; if it would overflow, loop again
prepout:        sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
output:         lda     $2              ; load character
                jsr     $e716           ;   and output
                ldx     $cf             ; check cursor phase
                beq     store           ; invisible -> to store
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and show
                ora     #$80            ;   cursor in
                sta     ($d1),y         ;   current row
                lda     $2              ; load character
store:          cli                     ; enable interrupts
                cmp     #$14            ; was it backspace/delete?
                beq     backspace       ; to backspace handling code
                cmp     #$d             ; was it enter/return?
                beq     done            ; then we're done.
                ldy     $fe             ; load buffer index
                sta     ($fc),y         ; store character in buffer
                iny                     ; advance buffer index
                sty     $fe
                bne     getkey          ; not zero -> ok
done:           lda     #$0             ; terminate string in buffer with zero
                ldy     $fe             ; get buffer index
                sta     ($fc),y         ; store terminator in buffer
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
                inc     $cc             ; disable cursor blinking
                cli                     ; enable interrupts
                rts                     ; return
backspace:      dec     $fe             ; decrement buffer index
                bcs     getkey          ; and get next key
.endproc

; parse / convert uint8 number using a BCD representation and double-dabble
.proc touint8
                sta     $fb
                sty     $fc
                ldy     #$0
                sty     convbuf
                sty     convbuf+1
                sty     convbuf+2
scanloop:       lda     ($fb),y
                beq     copy
                iny
                cmp     #$20
                beq     scanloop
                cmp     #$30
                bcc     error
                cmp     #$3a
                bcs     error
                bcc     scanloop
error:          sec
                rts
copy:           dey
                bmi     error
                ldx     #$2
copyloop:       lda     ($fb),y
                cmp     #$30
                bcc     copynext
                cmp     #$3a
                bcs     copynext
                sec
                sbc     #$30
                sta     convbuf,x
                dex
copynext:       dey
                bpl     copyloop
                lda     #$0
                sta     $fb
                ldx     #$8
loop:           lsr     convbuf
                lda     convbuf+1
                bcc     skipbit1
                ora     #$10
skipbit1:       lsr     a
                sta     convbuf+1
                lda     convbuf+2
                bcc     skipbit2
                ora     #$10
skipbit2:       lsr     a
                sta     convbuf+2
                ror     $fb
                dex
                beq     done
                lda     convbuf
                cmp     #$8
                bmi     nosub1
                sbc     #$3
                sta     convbuf
nosub1:         lda     convbuf+1
                cmp     #$8
                bmi     nosub2
                sbc     #$3
                sta     convbuf+1
nosub2:         lda     convbuf+2
                cmp     #$8
                bmi     loop
                sbc     #$3
                sta     convbuf+2
                bcs     loop
done:           lda     $fb
                clc
                rts
.endproc

```

# Answer
> 8 votes
# Python 2, 49 bytes

```
f=lambda n,t=1,p=1:n and p%t*t+f(n-p%t,t+1,p*t*t)

```

Uses Wilson's theorem, (as introduced to the site by xnor, I believe here)

**Try it online!**

The function `f` is recursive, with an initial input of `n` and a tail when `n` reaches zero, yielding that zero (due to the logical `and`); `n` is decremented whenever `t`, a test number which increments with every call to `f`, is prime. The prime test is then whether \\$(n-1)!\ \equiv\ -1 \pmod n\\$ for which we keep a track of a square of the factorial in `p`.

# Answer
> 7 votes
# Jelly, 4 bytes

My first Jelly program

```
RÆNS

```

Try it online!

# Answer
> 6 votes
# Java 8, ~~89~~ 78 bytes

```
n->{int r=0,i=2,t,p;for(;n>0;r+=t<2?p+0*n--:0)for(p=t=i++;p%--t>0;);return r;}

```

Try it online.

**Explanation:**

```
n->{               // Method with integer as both parameter and return-type
  int r=0,         //  Result-sum, starting at 0
      i=2,         //  Iteration-integer, starting at 2
      t,p;         //  Temp integers
  for(;n>0         //  Loop as long as `n` is still larger than 0:
      ;            //    After every iteration:
       r+=t<2?     //     If `t` is 1 (which means `p` is a prime):
           p       //      Increase `r` by `p`
           +0*n--  //      And decrease `n` by 1
          :        //     Else:
           0)      //      Both `r` and `n` remain the same
    for(p=t=i++;   //   Set both `p` and `t` to the current `i`,
                   //   and increase `i` by 1 afterwards with `i++`
        p%--t>0;); //   Decrease `t` by 1 before every iteration with `--t`,
                   //   and continue looping as long as `p` is NOT divisible by `t`
  return r;}       //  Return the result-sum

```

# Answer
> 5 votes
# 05AB1E, 3 bytes

```
ÅpO

```

Try it online.

**Explanation:**

```
Åp     # List of the first N primes (N being the implicit input)
       #  i.e. 5 → [2,3,5,7,11]
  O    # Sum of that list
       #  i.e. [2,3,5,7,11] → 28

```

# Answer
> 5 votes
# Brachylog, ~~8~~ 7 bytes

```
~lṗᵐ≠≜+

```

Try it online!

Saved 1 byte thanks to @sundar.

### Explanation

```
~l        Create a list of length input
  ṗᵐ      Each element of the list must be prime
    ≠     All elements must be distinct
     ≜    Find values that match those constraints
      +   Sum

```

# Answer
> 5 votes
# Perl 6, 31 bytes

```
{sum grep(&is-prime,2..*)[^$_]}

```

Try it online!

The `is-prime` built-in is unfortunately long.

# Answer
> 5 votes
# , 8 bytes

```
1#.p:@i.

```

Try it online!

# Answer
> 4 votes
# Husk, 4 bytes

```
Σ↑İp

```

Try it online!

Generates the **İ**nfinite list of **p**rime numbers, and computes the sum of the first \\$N\\$ (`Σ↑`)

# Answer
> 3 votes
# Attache, 10 bytes

```
Sum@Primes

```

Try it online!

ho hum

# Answer
> 2 votes
# Retina, 41 bytes

```
K`_
"$+"{`$
$%"_
)/¶(__+)\1+$/+`$
_
^_

_

```

Try it online! I wanted to keep adding 1 until I had found `n` primes but I couldn't work out how to do that in Retina so I resorted to a nested loop. Explanation:

```
K`_

```

Start with 1.

```
"$+"{`

```

Loop `n` times.

```
$
$%"_

```

Make a copy of the previous value, and increment it.

```
)/¶(__+)\1+$/+`$
_

```

Keep incrementing it while it's composite. (The `)` closes the outer loop.)

```
^_

```

Delete the original `1`.

```
_

```

Sum and convert to decimal.

# Answer
> 2 votes
# MATL, 4 bytes

```
:Yqs

```

Try it online!

### Explanation:

```
       % Implicit input: 5
:      % Range: [1, 2, 3, 4, 5]
 Yq    % The n'th primes: [2, 3, 5, 7, 11]
   s   % Sum: 28

```

# Answer
> 2 votes
# Ruby, 22 + 7 = 29 bytes

Run with `ruby -rprime` (+7)

```
->n{Prime.take(n).sum}

```

# Answer
> 2 votes
# PHP, 66 bytes

using my own prime function again ...

```
for(;$k<$argn;$i-1||$s+=$n+!++$k)for($i=++$n;--$i&&$n%$i;);echo$s;

```

Run as pipe with `-nr` or try it online.

**breakdown**

```
for(;$k<$argn;      # while counter < argument
    $i-1||              # 3. if divisor is 1 (e.g. $n is prime)
        $s+=$n              # add $n to sum
        +!++$k              # and increment counter
    )
    for($i=++$n;        # 1. increment $n
        --$i&&$n%$i;);  # 2. find largest divisor of $n smaller than $n:
echo$s;             # print sum

```

# Answer
> 2 votes
# Haskell, 48 bytes

```
sum.(`take`[p|p<-[2..],all((>0).mod p)[2..p-1]])

```

Try it online!

**Note:** `\p-> all((>0).mod p)[2..p-1]` is not a valid prime check, since it is `True` for \\$0,1\\$ as well. But we can work around that by beginning with \\$2\\$, so in this case it suffices.

# Answer
> 2 votes
# Pari/GP, 20 bytes

```
n->vecsum(primes(n))

```

Try it online!

# Answer
> 2 votes
# C (gcc), 70 bytes

```
f(n,i,j,s){s=0;for(i=2;n;i++)for(j=2;j/i?s+=i,n--,0:i%j++;);return s;}

```

Try it online!

# Answer
> 2 votes
# Japt `-x`, 11 bytes

```
;@_j}a°X}hA

```

Try it online!

Saved several bytes thanks to a new language feature.

Explanation:

```
;@      }hA    :Get the first n numbers in the sequence:
     a         : Get the smallest number
      °X       : Which is greater than the previous result
  _j}          : And is prime
               :Implicitly output the sum

```

# Answer
> 2 votes
## C, C++, D : ~~147~~ 142 bytes

```
int p(int a){if(a<4)return 1;for(int i=2;i<a;++i)if(!(a%i))return 0;return 1;}int f(int n){int c=0,v=1;while(n)if(p(++v)){c+=v;--n;}return c;}

```

### 5 bytes optimization for C and C++ :

-2 bytes thanks to Zacharý

```
#define R return
int p(int a){if(a<4)R 1;for(int i=2;i<a;++i)if(!(a%i))R 0;R 1;}int f(int n){int c=0,v=1;while(n)if(p(++v))c+=v,--n;R c;}

```

`p` tests if a number is a prime, `f` sums the `n` first numbers

Code used to test :

C/C++ :

```
for (int i = 0; i < 10; ++i)
    printf("%d => %d\n", i, f(i));

```

## D Optimized answer by Zacharý, ~~133~~ 131 bytes

D has a golfy template system

```
T p(T)(T a){if(a<4)return 1;for(T i=2;i<a;)if(!(a%i++))return 0;return 1;}T f(T)(T n){T c,v=1;while(n)if(p(++v))c+=v,--n;return c;}

```

# Answer
> 2 votes
# Factor \+ `math.primes math.unicode`, 14 bytes

```
[ nprimes Σ ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes an integer as input and leaves an integer as output.

* `nprimes` Obtain a list of the first n primes.
* `Σ` Sum the list.

# Answer
> 2 votes
# , 106 bytes

```
T f(T)(T n){T p(T a){T b=1;for(T i=2;i<a;)b*=a%i++;return b;}T c,v=1;while(n)if(p(++v))c+=v,--n;return c;}

```

Try it online!

Based on my previous revisions to HatsuPointerKun's C++ answer.

# Answer
> 1 votes
# JavaScript (ES6), 55 bytes

```
f=(k,n=2)=>k&&(g=d=>n%--d?g(d):d<2&&k--&&n)(n)+f(k,n+1)

```

Try it online!

# Answer
> 1 votes
# Stax, 6 bytes

```
ê☺Γ☼èY

```

Run and debug it

Explanation:

```
r{|6m|+ Unpacked program, implicit input
r       0-based range
 {  m   Map:
  |6      n-th prime (0-based)
     |+ Sum
        Implicit output

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 7 + 9 = 16 bytes

```
+/pco∘⍳

```

Try it online!

9 additional bytes to import the `pco` (and every other) Dfn: `⎕CY'dfns'`

### How:

```
+/pco∘⍳
      ⍳ ⍝ Generate the range from 1 to the argument
     ∘  ⍝ Compose
  pco   ⍝ P-colon (p:); without a left argument, it generates the first <right_arg> primes.
+/      ⍝ Sum

```

# Answer
> 1 votes
# JAEL, 5 bytes

```
#&kȦ

```

### Explanation (generated automatically):

```
./jael --explain '#&kȦ'
ORIGINAL CODE:  #&kȦ

EXPANDING EXPLANATION:
Ȧ => .a!

EXPANDED CODE:  #&k.a!,

#     ,                 repeat (p1) times:
 &                              push number of iterations of this loop
  k                             push nth prime
   .                            push the value under the tape head
    a                           push p1 + p2
     !                          write p1 to the tape head
       ␄                print machine state

```

# Answer
> 1 votes
# Japt `-x`, ~~8~~ 5 bytes

```
Èj}jU

```

Try it

```
Èj}jU     :Implicit input of integer U
È         :Function taking an integer as argument
 j        :  Is prime?
  }       :End function
   jU     :First U integers >=0 that return true
          :Implicit output of sum of resulting array

```

# Answer
> 1 votes
# Reticular, ~~52~~ 40 bytes

```
indQ2j;o_1-2~d:^=[d@P~1-]:^`*[+]:^`1+*o;

```

Try it online!

## Explanation

Fun fact: Reticular does not count 2 as a prime number, so the instruction `@P` which gives the \\$n\\$-th prime in reality gives the \\$(n+1)\\$-th prime and due to this we have to add the first prime 2 manually.

```
in           # Read input and convert to int
dQ2j;o_      # Check if input is 0. If so, output and exit
1-2~d:^=     # Subtract 1 from input and save it as  `^`
[d@P~1-]     # Duplicate the top of the stack (call it k)
               and push the k-th prime. Finally swap the two top items
               in the stack and subtract 1.
               Stack before: [k]
               Stack after: [k-1, k-th prime]
:^`*         # Repeat the above a `^` number of times.
               Stack before: [n]
               Stack after: [0, 3, 5, ...,  n-th prime, 2]
[+]:^`1+*    # Add the two top items in the stack a
               total of (`^`+1) number of times
o;           # Output the sum and exit.

```

# Answer
> 1 votes
# Vyxal, 2 bytes, `s`

```
ʁǎ

```

Try it!

**Explanation**

```
ʁ  # Range from 0 to input
ǎ  # Map to a_th prime

```

At last, sum with `s` flag

*Disclaimer: my first Vyxal answer*

# Answer
> 1 votes
# Pyt, 3 bytes

```
řᵽƩ

```

Try it online!

```
ř       implicit input (n); creates array of [1,2,...,n]
 ᵽ      gets the kth prime for each item k in the array
  Ʃ     sums the array; implicit print

```

# Answer
> 1 votes
# Arturo, 38 bytes

```
$[n][sum take select 2..n*n=>prime? n]

```

Try it

# Answer
> 0 votes
# Python 2, ~~63~~ ~~59~~ ~~56~~ 51 bytes

```
f=lambda n:n and prime(n)+f(n-1)
from sympy import*

```

Try it online!

---

Saved:

* -5 bytes, thanks to Jonathan Allan

---

Without libs:

# Python 2, 83 bytes

```
n,s=input(),0
x=2
while n:
 if all(x%i for i in range(2,x)):n-=1;s+=x
 x+=1
print s

```

Try it online!

# Answer
> 0 votes
# Pyke, 4 bytes

```
~p>s

```

Try it here!

```
~p   -   prime_numbers
  >  -  first_n(^, input)
   s - sum(^)

```

# Answer
> 0 votes
# CJam, 21 bytes

```
0{{T1+:Tmp!}gT}li*]:+

```

```
Explanation:
0{{T1+:Tmp!}gT}li*]:+ Original code

 {            }li*    Repeat n times
  {        }          Block
   T                  Get variable T | stack: T
    1+                Add one | Stack: T+1
      :T              Store in variable T | Stack: T+1
        mp!           Is T not prime?     | Stack: !(isprime(T))
            g         Do while condition at top of stack is true, pop condition
             T        Push T onto the stack | Stack: Primes so far
0                 ]   Make everything on stack into an array, starting with 0 (to not throw error if n = 0)| Stack: array with 0 and all primes up to n
                   :+ Add everything in array

```

Try it online!

# Answer
> 0 votes
## F#, 111 bytes

```
let f n=Seq.initInfinite id|>Seq.filter(fun p->p>1&&Seq.exists(fun x->p%x=0){2..p-1}|>not)|>Seq.take n|>Seq.sum

```

Try it online!

`Seq.initInfinite` creates an infinitely-long sequence with a generator function which takes, as a parameter, the item index. In this case the generator function is just the identity function `id`.

`Seq.filter` selects only the numbers created by the infinite sequence that are prime.

`Seq.take` takes the first `n` elements in that sequence.

And finally, `Seq.sum` sums them up.

# Answer
> 0 votes
# cQuents, 3 bytes

```
;pz

```

Try it online!

## Explanation

```
;    sum of first n terms for input n
 pz  each term is the next prime after the previous term

```

# Answer
> 0 votes
# MY, 4 bytes

```
⎕ṀΣ↵

```

Try it online!

Still regretting no implicit input/output in this garbage language, would've been two bytes otherwise.

* = input
* = 1st ... nth prime inclusive
* `Σ` = sum
* = output

# Answer
> 0 votes
# APL(NARS), 27 chars, 54 bytes

```
{⍵=0:0⋄+/{⍵=1:2⋄¯2π⍵-1}¨⍳⍵}

```

{¯2π⍵} here would return the n prime different from 2. So {⍵=1:2⋄¯2π⍵-1} would return the n prime 2 in count in it...

# Answer
> 0 votes
# Pyth, 5 bytes

```
s.fP_

```

Try it online here.

```
s.fP_ZQ   Implicit: Q=eval(input())
          Trailing ZQ inferred
 .f   Q   Starting at Z=1, return the first Q numbers where...
   P_Z    ... Z is prime
s         Sum the resulting list, implicit print

```

# Answer
> 0 votes
# Thunno 2 `S`, 2 bytes

```
Æp

```

Try it online!

Built-in for "first n primes". `S` flag sums the list.

---
Tags: code-golf, primes
---


title: Odd'em out: letters

text:
# Question
Title: Odd'em out: letters
## Objective

Write a program or function (or equivalent) that sorts out and returns the odd letter in the matrix of random size.

## Details

You will be passed a matrix (as a string) as input of random dimensions such as this.

```
bbbbbbbbbb
bbbbbdbbbb
bbbbbbbbbb
bbbbbbbbbb
bbbbbbbbbb

```

Your job is to find the letter that doesn't match the rest (in this case, it is `d`, found at line 2, col 6) and to return that letter as output. The matrix will consist of letters `A-Z`, `a-z`, newlines (`\n`, only on ends of rows) and have dimensions ranging from 5x5 to 10x10 (25-100 letters).

Standard loopholes apply. This is a code golf challenge; entry with code of least bytes wins.

## Input

Input will be passed in through standard input as a string if it is a program or as an argument if a function (or similar).

## Output

A single character that is the "odd" in the matrix *or* `None`, `nil`, `NUL`, or the string `"None"` if there is no "odd" character.

## More Examples

```
AAAAAAA
AAAAAAA
AAAAAAA
AAAIAAA
AAAAAAA

```

Answer: `I`

```
vvqvvvvvvv
vvvvvvvvvv
vvvvvvvvvv
vvvvvvvvvv
vvvvvvvvvv

```

Answer: `q`

```
puuuuuuuu
uuuuuuuuu
uuuuuuuuu
uuuuuuuuu
uuuuuuuuu
uuuuuuuuu
uuuuuuuuu
uuuuuuuuu
uuuuuuuuu
uuuuuuuuu

```

Answer: `p`

## Generator

Here is a random matrix generator written in Python that you can use to test your program. **Note:** There is a slight chance that it could make a mistake and not put in an odd letter.

```
Instructions

1. Copy this code into a file called `matrix_gen.py`.
2. Run it with `python matrix_gen.py`.

---

from random import randint

rows = randint(5,10)
cols = randint(5,10)

charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
neg = charset[randint(0,51)]
pos = charset[randint(0,51)]
p_used = 0

comp = 0
matrix = ""

while comp < rows:
  row = ""
  while len(row) < cols:
    if not p_used and not randint(0,10):
      p_used = 1
      row = row + pos
    else:
      row = row + neg
  row = row + "\n"
  matrix = matrix + row
  comp += 1

print matrix[:-1]
```

# Answer
# Python 3, 27 bytes

```
lambda x:min(x,key=x.count)

```

Try it online!
> 14 votes

# Answer
# , ~~12 10~~ 7 bytes

```
-.}./.~

```

Try it online!

```
    /.~        Group identical items together
  }.           Remove one item from each group
-.             Remove the rest from the input

```

### 10 byte version

```
-._1 1{\:~

```

hisss...

```
       \:~        Sort down
  _1 1{           Take the last character (which is a newline) and the second one.
-.                Remove those from the input

```
> 6 votes

# Answer
# Brachylog, ~~8~~ 4 bytes

```
oḅ∋≠

```

Try it online!

## Explanation

I haven't used Brachylog before, so this may not be optimal.

```
oḅ∋≠  Input is a string.
o     Sort the input.
 ḅ    Split it into blocks of equal elements.
  ∋   There is a block
   ≠  whose elements are all different.
      That block is the output.

```
> 5 votes

# Answer
# 05AB1E,  ~~4~~  2 bytes

Saved 2 bytes thanks to *Adnan*

```
.m

```

Try it online!

**Explanation**

```
.m   # push a list of the least frequent character(s) in input

```
> 4 votes

# Answer
# K (oK), ~~7~~ 6 bytes

**Solution**

```
*<#:'=

```

Try it online!

**Example:**

```
*<#:'="vvqvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv"
"q"

```

**Explanation:**

Found a slightly shorter approach: Evaluated right-to-left:

```
*<#:'= / the solution
     = / group matching items together
  #:'  / count (#:) each (')
 <     / sort ascending
*      / take the first one

```

**Notes:**

Whilst I'm expecting the bonus aspect of this challenge to get dropped, this solution will return the newline character `\n` if there is no odd character:

```
*<#:'="vvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv"
"\n"

```
> 3 votes

# Answer
# C (gcc), ~~93~~ ~~92~~ ~~90~~ ~~66~~ 62 Bytes

Much shorter as a function

```
t;f(char*p){for(t=*p;*p;)t^*p++?putchar(*p^*--p?*p:t),*p=0:0;}

```

Try it online!

test code

```
main()
{
    char s[99];
    for(;gets(s);)f(s);
}

```

old version is a program

# C 86 Bytes

```
char*p;s[9];main(t){for(;p=gets(s);)for(t=*p;*p;)t^*p++?putchar(*p^*--p?*p:t),*p=0:0;}

```

Outputs the odd character, or nothing. run like this;

```
C:\eng\golf>python matrix_gen.py | a.exe
X
C:\eng\golf>python matrix_gen.py | a.exe
G
C:\eng\golf>python matrix_gen.py | a.exe
x
C:\eng\golf>python matrix_gen.py | a.exe

C:\eng\golf>python matrix_gen.py | a.exe
J

```
> 3 votes

# Answer
# Prolog (SWI), 46 bytes

```
p(L):-select(X,L,Y),\+member(X,Y),writef([X]).

```

Try it online!

Or if the standard **true** output from prolog queries is not okay:

# Prolog (SWI), 48 bytes

```
Z*L:-select(X,L,Y),\+member(X,Y),char_code(Z,X).

```

Try it online!

**Explanation**

```
Find the first element X in the input
that when removed, results in output
that does not contain X

then depending on the version above either:
print X as a character
or
return X as an atom

```
> 3 votes

# Answer
# C, 94 bytes

Return by pointer. If none, return `\0`.

This will cause memory leaks. Assuming `int` is 4 bytes.

```
*t;f(c,p,i)char*c,*p;{t=calloc(64,8);for(*p=-1;*c;c++)t[*c]--;for(i=0;++i<128;)!~t[i]?*p=i:0;}

```

Try it online!
> 2 votes

# Answer
# Mathematica, 27 bytes

```
Last@*Keys@*CharacterCounts

```

Try it online!

*-1 byte from Martin Ender*
> 2 votes

# Answer
## Retina, 13 bytes

```
s(O`.
(.)\1+

```

Try it online!

### Explanation

```
s(O`.

```

Sort all characters.

```
(.)\1+

```

Remove any characters that appear at least twice.
> 2 votes

# Answer
# Bash, ~~15~~ 20 bytes

```
fold -1|sort|uniq -u

```

Try it online!

**Explanation:** `fold`s the input to `1` character per line, `sort`s it into groups of matching letters, then prints only lines that are `uniq`ue.

*Thanks @Nahuel Fouilleul for catching and helping fix a problem with this approach.*
> 2 votes

# Answer
# Husk, 2 bytes

```
◄=

```

Try it online!

This is a function taking a string as input and returning a character. It takes the minimum of the input string when comparing characters for equality (i.e. it returns the character that is equal to the least number of other characters).
> 2 votes

# Answer
# JavaScript (ES6), 37 bytes

Returns `null` if there's no odd letter.

```
s=>s.match(`[^
${s.match(/(.)\1/)}]`)

```

### Test cases

```
let f =

s=>s.match(`[^
${s.match(/(.)\1/)}]`)

console.log(f(
  'bbbbbbbbbb\n' +
  'bbbbbdbbbb\n' +
  'bbbbbbbbbb\n' +
  'bbbbbbbbbb\n' +
  'bbbbbbbbbb'
))

console.log(f(
  'AAAAAAA\n' +
  'AAAAAAA\n' +
  'AAAAAAA\n' +
  'AAAIAAA\n' +
  'AAAAAAA'
))

console.log(f(
  'vvqvvvvvvv\n' +
  'vvvvvvvvvv\n' +
  'vvvvvvvvvv\n' +
  'vvvvvvvvvv\n' +
  'vvvvvvvvvv'
))

console.log(f(
  'puuuuuuuu\n' +
  'uuuuuuuuu\n' +
  'uuuuuuuuu\n' +
  'uuuuuuuuu\n' +
  'uuuuuuuuu\n' +
  'uuuuuuuuu\n' +
  'uuuuuuuuu\n' +
  'uuuuuuuuu\n' +
  'uuuuuuuuu\n' +
  'uuuuuuuuu'
))

console.log(f(
  'AAAAA\n' +
  'AAAAA\n' +
  'AAAAA\n' +
  'AAAAA\n' +
  'AAAAA'
))
```
> 1 votes

# Answer
# Jelly, 4 bytes

```
ċ@ÐṂ

```

Try it online!

Return `\n` (a single newline) in case there is no odd character. Obviously `\n` is not a printable character.

Coincidentally this is exactly the same algorithm as Mr.Xcoder Python answer. (I came up with it independently)

Explanation:

```
  ÐṂ    Ṃinimum value by...
ċ@      ċount. (the `@` switch the left and right arguments of `ċ`)

```

That works because in a `m×n` matrix:

* If there exists odd character: There are `m-1` newlines, 1 odd characters and `m×n-1` normal character, and `1 < m-1 < m×n-1` because `5 ≤ m, n ≤ 10`.
* If there doesn't exist odd character: There are `m-1` newlines and `m×n` normal character, and `m-1 < m×n`.
> 1 votes

# Answer
# Pyth, 4 bytes

```
ho/Q

```

**Try it here!**
> 1 votes

# Answer
# Japt `-h`, ~~6~~ 4 bytes

```
ü l1

```

Try it

```
ü l1     :Implicit input of multiline string
ü        :Group & sort
  l1     :Filter elements of length 1
         :Implicit output of last element

```
> 1 votes

# Answer
# Perl 5, 17 + 3 (-00p) -25% = 15 bytes

```
/(.)\1/;s/
|$1//g

```

try it online
> 1 votes

# Answer
# Octave, ~~26~~ 25 bytes

*1 byte saved thanks to @Giuseppe*

```
@(x)x(sum(x(:)==x(:)')<2)

```

Anonymous function that takes a 2D char array as input, and outputs either the odd letter or an empty string if it doesn't exist.

**Try it online!**
> 1 votes

# Answer
## Haskell, 33 * 0.75 = 24.75 bytes

```
f s=[c|[c]<-(`filter`s).(==)<$>s]

```

Returns an empty list if there's no odd character.

Try it online!

For each char `c` in the matrix (given as a string `s`) make a string of all chars in `s` that are equal to `c` and keep those of length 1.
> 1 votes

# Answer
# Common Lisp, 47 bytes

```
(lambda(s)(find-if(lambda(x)(=(count x s)1))s))

```

Try it online!

Returns the odd letter or NIL if it does not exist.
> 1 votes

# Answer
# C (gcc), ~~91~~ ~~86~~ ~~82~~ ~~79~~ 71 bytes

```
f(char*s){for(;*++s==10?s+=2:0,*s;)if(*s^s[-1])return*s^s[1]?*s:s[-1];}

```

Try it online!

* Thanks to **Gastropner** for the xor and ? tricks (-3 bytes)
* Reworked the compare version to fix bugs and used **Gastropner** magic from comments.

**Explanation:**

Compare current and previous char while skipping newlines. If different, compare to next char. This tells us if we return current or previous char. The function returns the "odd" char value if it exists or 0 if the array is not odd. We get away with the "next" char check because there is always a newline before the `\0` char. If there is no odd char, we intrinsically return the \0 from the for loop.

---

**Older, sexier xor code Explanation:**

Make a running xor mask of the next 3 string values. If they are all the same, then the value will be equal to any of the three. If they are different, then the 2 identical will cancel each other out leaving the unique.

Must factor /n before the xor or it gets messy. Also have to check 2 chars for inequality in case s\[0\] is the odd value. This costs the extra || check.

```
v;f(char*s){while(s[3]){s[2]==10?s+=3:0;v=*s^s[1]^s[2];if(v^*s++||v^*s)break;}}

```
> 1 votes

# Answer
# Matlab, 25 Bytes

```
a=input('');a(a~=mode(a))

```

The input "a" where "a" isn't the mode of "a". Outputs empty array for no oddball.
> 1 votes

# Answer
# Java 8, 85 bytes

This is a lambda from `String` to `String` (e.g. `Function<String, String>`). It's essentially a copy of Luca's solution, but I've pared down the string sorting a bit.

```
s->new String(s.chars().sorted().toArray(),0,s.length()).replaceAll("(.)\\1+|\\n","")

```

Try It Online
> 1 votes

# Answer
# C# (.NET Core), 54 bytes

```
i=>i.GroupBy(x=>x).FirstOrDefault(g=>g.Count()<2)?.Key

```

Try it online!
> 1 votes

# Answer
# Stax, 2 bytes

```
|!

```

Run and debug it
> 1 votes

# Answer
# Alice, 16 * 75% = 12 bytes

```
/-.nDo&
\i..*N@/

```

Try it online!

Outputs `Jabberwocky` if there is no duplicate character.

### Explanation

```
/...@
\.../

```

This is a framework for linear programs that operate entirely in Ordinal (string processing mode). The actual code is executed in a zigzag manner and unfolds to:

```
i..DN&-o

i   Read all input.
..  Make two copies.
D   Deduplicate one copy, giving only the two letters and a linefeed.
N   Multiset difference. Removes one copy of each letter and one linefeed.
    Therefore it drops the unique letter.
&-  Fold substring removal over this new string. This essentially removes
    all copies of the repeated letter and all linefeeds from the input,
    leaving only the unique letter.
.   Duplicate.
n   Logical NOT. Turns empty strings into "Jabberwocky" and everything else
    into an empty string.
*   Concatenate to the previous result.
o   Print the unique letter or "Jabberwocky".

```

Instead of `&-`, we could also use `ey` (transliteration to an empty string). Alternatively, by spending one more character on stack manipulation, we could also deduplicate the input which lets us remove the unwanted characters with `N`, but it's still the same byte count:

```
i.D.QXN.n*o@

```

## Alice, 13 bytes

```
/N.-D@
\i&.o/

```

Try it online!

This is the solution without the bonus, it's simply missing the `.n*`.
> 0 votes

# Answer
# Retina, 22 bytes

```
!`(.)(?!.*\1)(?<!\1.+)

```

Try it online! Only requires height and width of at least 3, rather than 5.
> 0 votes

# Answer
# APL+WIN, 16 bytes

```
(1=+/a∘.=a)/a←,⎕

```

Prompts for screen input and either outputs odd letter or nothing if there is no odd letter
> 0 votes

# Answer
# PowerShell, 39 bytes

```
([char[]]"$args"|group|sort c*)[0].Name

```

Try it online!

Takes input as a string with newlines (as specified in the challenge), converts it to a `char`-array. We then `Group-Object` the characters, so that characters are grouped together by their names, then `sort` based on the `c`ount. This ensures that the lonely character is first, so we take the `[0]` index and output its `.Name`.

If newline is acceptable for "nothing" then this qualifies for the bonus.
> 0 votes

# Answer
# Perl 6,  ~~27~~  24 -25% = 18 bytes

```
*.comb.Bag.min(*.value).key

```

Test it

```
{%(.comb.Bag.invert){1}}

```

Test it

This will return an undefined value when given an input that doesn't have an odd character out.

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  %(        # coerce into a Hash

    .comb   # split the input into graphemes (implicit method call on ｢$_｣)
    .Bag    # turn into a weighted Set
    .invert # invert that (swap keys for values) returns a sequence

  ){ 1 }    # get the character that only occurs once
}

```
> 0 votes

# Answer
# Java (OpenJDK 8), ~~93~~ ~~98~~ 108 bytes

```
a->{char[]r=a.toCharArray();java.util.Arrays.sort(r);return String.valueOf(r).replaceAll("(.)\\1+|\\n","");}

```

Try it online!

The input is converted to an array of characters, which is then sorted. We have to make a string again so we can replace all occurences matching the regex.

I first tried to simply do it with one "replaceAll" but I did not manage to create a regex that would delete the first a in "abaa" for example.
> 0 votes

# Answer
# , 61 bytes

```
cat(names(sort(table(unlist(strsplit(scan(,""),""))),T))[-1])

```

Try it online!

Takes input from stdin, outputs the letter (or the empty string) to stdout.

Explanation:

```
x=scan(,"")                     # read in input
x=unlist(strsplit(x,""))        # split into characters
x=table(x)                      # tabulate character counts
x=sort(x,T)                     # sort into decreasing order
x=names(x)                      # get the names (the characters)
x=x[-1]                         # remove the first element
cat(x)                          # print out the remaining letter (or nothing if none exist)

```
> 0 votes

# Answer
# Brainfuck, 125 bytes

```
,[----------[>],]<[->+<]<<[[->->+<<]>[>[->-<<<+>>]>[,<<,>>]<<<[->+<]>[->+<]<]>[-<<+>>]>[-<+>]<<<<]>>>>[<]<++++++++++.

```

Try It Online

Prints the letter of the matrix if there is no odd one out
> 0 votes

# Answer
# PHP, 74 bytes

**normal program, 57 bytes:**

```
<?=chr(array_search(min($a=count_chars($argv[1],1)),$a));

```

(prints a newline if the is no odd character)

**modified program, 74 bytes:**

```
<?=count($a=count_chars($argv[1],1))<4?None:chr(array_search(min($a),$a));

```

(assumes Windows linebreaks; replace `4` with `3` for input with Unix linebreaks)

Run with `php <scriptname> '<matrix>'` or try then online.
> 0 votes

# Answer
# Ruby, 33 bytes

```
->s{s.chars.min_by{|c|s.count c}}

```

Try it online!

Uses the same idea as Mr. Xcoder's great Python answer.
> 0 votes

# Answer
# Arturo, 36 bytes

```
$[s][select s'c->one? match s~"|c|"]

```

Try it
> 0 votes

# Answer
# , 17 bytes

```
~.{~[:(i.<./)#/.~

```

Outputs the odd character or LF.

Attempt This Online!

```
~.{~[:(i.<./)#/.~
    [:             NB. [: f g forces f(g(y))
             #/.~  NB. character frequency
      (i.<./)      NB. monadic hook
         <./       NB. minimum
       i.          NB. index of minimum in frequency list
  {~               NB. index from
~.                 NB. unique characters

```
> 0 votes

# Answer
# Thunno `DD`, \\$ 10 \log\_{256}(96) \approx \\$ 8.23 bytes

```
dcZZz;AKAK

```

Attempt This Online!

#### Explanation

```
dcZZz;AKAK  # Implicit input
dc          # Count of each character
  ZZ        # Zip with input
    z;      # Reverse-sort this list
      AKAK  # Last item of last item
            # Implicit output

```
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
æcḅ

```

Try it online!

#### Explanation

```
æcḅ  # Implicit input
æ    # Filter by:
 c   #  Count in input
  ḅ  #  Equals one
     # Implicit output

```
> 0 votes

---
Tags: code-golf, sorting, matrix, alphabet
---


title: Evenly spread values

text:
# Question
Title: Evenly spread values
Given a sorted list of unique positive floats (none of which are integers) such as:

```
[0.1, 0.2, 1.4, 2.3, 2.4, 2.5, 3.2]

```

Evenly spread out the values that fall between two consecutive integers. So in this case you would get:

```
[0.333, 0.666, 1.5, 2.25, 2.5, 2.75, 3.5]

```

(I have truncated the values 1/3 and 2/3 for ease of presentation.)

# Answer
> 8 votes
# Nekomata, 8 bytes

```
kŢᵉR→/+j

```

Attempt This Online!

Input and output are both in fractions, because Nekomata doesn't have floating point numbers.

```
kŢᵉR→/+j
k           Floor
                e.g. [1/10,2/10,14/10,23/10,24/10,25/10,32/10] -> [0,0,1,2,2,2,3]
 Ţ          Tally; returns a list of unique elements and a list of their counts
                e.g. [0,0,1,2,2,2,3] -> [0,1,2,3], [2,1,3,1]
  ᵉR        Range each count, and push the original list
                e.g. [2,1,3,1] -> [[1,2],[1],[1,2,3],[1]], [2,1,3,1]
    →       Increment
                e.g. [2,1,3,1] -> [3,2,4,2]
     /      Divide
                e.g. [[1,2],[1],[1,2,3],[1]], [3,2,4,2] -> [[1/3,2/3],[1/2],[1/4,1/2,3/4],[1/2]]
      +     Add
                e.g. [0,1,2,3], [[1/3,2/3],[1/2],[1/4,1/2,3/4],[1/2]] -> [[1/3,2/3],[3/2],[9/4,5/2,11/4],[7/2]]
       j    Join
                e.g. [[1/3,2/3],[3/2],[9/4,5/2,11/4],[7/2]] -> [1/3,2/3,3/2,9/4,5/2,11/4,7/2]

```

# Answer
> 8 votes
# , ~~46~~ 45 bytes

*Edit: -1 byte thanks to pajonk*

```
\(x)sequence(y<-rle(t<-x%/%1)$l)/rep(y+1,y)+t

```

Attempt This Online!

A rare use for R's obscure `sequence` function: "For each element of `x` the sequence `1...x` is created. These are concatenated and the result returned."

The documentation also notes: "`sequence` mainly exists in reverence to the very early history of R."

# Answer
> 6 votes
# APL (Dyalog Unicode), ~~18~~ 16 bytes

```
∊⌊(⊂⊣+⍋⍤⊢÷≢⍤,)⌸⊢

```

Try it online! (Using Extended because TIO is out of date)

`⌊(``)⌸⊢` on each unique floor () and its corresponding argument elements ():

enclose the

left argument, i.e. the floor in question

`+` added to

`⍋⍤⊢` the grade ( sorting permutation: 1…length) of () the right argument ( the elements)

`÷` divided by

`≢⍤,` the count () of () the concatenation (`,`) of the floor and the elements

**e**nlist (flatten)

# Answer
> 6 votes
# 05AB1E, 10 bytes

```
ïγεā¤>/+}˜

```

Try it online or try it online with step-by-step debug-lines.

**Explanation:**

```
ï         # Floor all values in the (implicit) input-list
 γ        # Group it into adjacent equal values
  ε       # Map over each group:
   ā      #  Push a list in the range [1,length] (without popping the list)
    ¤     #  Push its last item - the length (without popping the list)
     >    #  Increase this length by 1
      /   #  Divide all values in the [1,length]-ranged list by this (length+1)
       +  #  Add it to each floored value of the current group
  }˜      # After the map: flatten the list of lists
          # (after which the result is output implicitly)

```

# Answer
> 5 votes
# Octave, 45 bytes

```
@(x)(t=fix(x))+sum(triu(u=t==t'))./(sum(u)+1)

```

Try it online!

### Explanation

```
@(x)(t=fix(x))+sum(triu(u=t==t'))./(sum(u)+1)

@(x)                                           % Anonymuous function
    (t=fix(x))                                 % t: round down x, element-wise
                        u=t==t'                % u: matrix of pairwise comparisons of t
                   triu(       )               % Upper triangular part of u
               sum(            )               % Sum of each column of that
                                    sum(u)+1   % Sum of each column of u, plus 1
                                 ./(        )  % Divide, elemment-wise
              +                                % Add, element-wise

```

# Answer
> 4 votes
# Jelly, 11 bytes

```
ḞJ÷L‘$+Ʋƙ`F

```

Try it online!

# Answer
> 4 votes
# Python, 95 bytes

```
lambda x:[k+~j/~len(i)for k,[*i]in groupby(x,int)for j in range(len(i))]
from itertools import*

```

Attempt This Online!

# Answer
> 4 votes
# Vyxal, 64 bitsv2, 8 bytes

```
⌊øĖ₌ɾ›/+f

```

Try it Online!

*-2 thanks to emanresu*

## Explained

```
⌊Ġ:@₌ɾ›/+f
⌊Ġ          # Group the floored values by consecutive items.
  :@        # Push a copy of that where each item is the corresponding length.
    ₌ɾ›     # Push a list [range 1..n for n in top], [n+1 for n in top]
       /    # And divide those lists.
        +   # Add that to the original grouped values
         f  # Then flatten

```

Created with the help of Luminespire.

# Answer
> 4 votes
# JavaScript (Node.js), 61 bytes

```
x=>x.map(k=v=>(k[v|=0]=~-k[v])/~x.filter(t=>~~t==v).length+v)

```

Try it online!

# JavaScript (Node.js), 65 bytes

```
x=>x.map(k=v=>(k[v|=0]=-~k[v],v)).map(m=v=>v+(m[v]=~-m[v])/~k[v])

```

Try it online!

# Answer
> 4 votes
# Thunno 2 `S`, 9 bytes

```
Nġıżnl⁺/+

```

Try it online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
Nġıżnl⁺/+  # Implicit input
N          # Floor each value
 ġ         # Group consecutive
  ı        # Map over this list:
   ż       #  Without popping, push [1..length]
    nl     #  Length of the current group
      ⁺    #  Incremented
       /   #  Divide the range by this
        +  #  Add to the group
           # Implicit output, flattened

```

# Answer
> 3 votes
# JavaScript (ES6), 63 bytes

```
a=>a.map(p=v=>a.map(V=>v^V||n++,n=1,p!=(p=~~v)?q=1:q++)&&p+q/n)

```

Try it online!

### Commented

```
a =>                 // a[] = input array
a.map(p =            // initialize p to a NaN'ish value
  v =>               // for each value v in a[]:
  a.map(V =>         //   for each value V in a[]:
    v ^ V || n++,    //     increment n if floor(v) = floor(V)
    n = 1,           //     starting with n = 1
    p != (p = ~~v) ? //     if p is not equal to floor(v)
                     //     (update p to floor(v) afterwards):
      q = 1          //       start a new group with q = 1
    :                //     else:
      q++            //       increment q
  ) &&               //   end of inner map()
  p + q / n          //   the final value is p + q / n
)                    // end of outer map()

```

# Answer
> 3 votes
# , 47 bytes

```
\(x)ave(x,y<-x%/%1,FUN=\(z)seq(z)/sum(1,z^0))+y

```

Attempt This Online!

Not as short as the answer using `sequence`, but `ave` is pretty neat, too.

# Answer
> 2 votes
# Charcoal, 19 bytes

```
≦⌊θＩＥθ⁺ι∕⊕№…θκι⊕№θι

```

Try it online! Link is to verbose version of code. Explanation:

```
  θ                 Input array
≦                   Apply to all elements
 ⌊                  Floor
     θ              Floored array
    Ｅ               Map over floored elements
       ι            Current floored element
      ⁺             Plus
            θ       Floored array
           …        Truncated to length
             κ      Current index
          №         Count of
              ι     Current floored element
         ⊕          Incremented
        ∕           Divided by
                 θ  Floored array
                №   Count of
                  ι Current floored element
               ⊕    Incremented
   Ｉ                Cast to string
                    Implicitly print

```

# Answer
> 2 votes
# Perl 5, 61 bytes

```
sub{map{//;map{$'+$_/($c+1)}1..($c=grep$'==int,@_)}0..$_[-1]}

```

Try it online!

```
sub {
  map {                #loop ints in $_ from 0 to highest input number as int
    //;                #copies current $_ to $'
    $c=grep$'==int,@_; #$c = count of current int in $_ in input array @_
    map {              #loop 1 to current count in $c
      $' + $_ / ($c+1) #return current outer int + inner int / count+1
    }
    1..$c              #inner loop, no loop and no return if count is 0
  }
  0..$_[-1]            #outer loop
}

```

# Answer
> 1 votes
# Pyth, 16 bytes

```
=sMQm+c@XdH1d/+Q

```

Try it online!

### Explanation

```
=sMQm+c@XdH1d/+QdddQ    # implicitly add Q
                        # implicitly assign Q=eval(input()), H=dict()
=  Q                    # assign Q to
 sMQ                    # floor() mapped over Q
    m              Q    # map lambda d over Q
        XdH1            #   H[d]+=1 (or H[d]=1 if d not in H)
       @    d           #   H[d]
      c                 #   divided by
             /   d      #   the count of how many times d appears in
              +Qd       #   Q with d appended
     +            d     #   plus d

```

# Answer
> 1 votes
# , 21 bytes

```
<.+&;<.<@(#\%1+#)/.<.

```

Try it online!

Repetition of floor `<.` 3 times was surprisingly shorter than alternatives that DRY it out.

* `<..../.<.` For each group of the floor...
* `<@(#\%1+#)` Divide 1...g by (1 + g), where g is the group size. Box it `<@` because we have to box heterogeneous lists.
* `<.+&;` Add the floor elementwise to that unboxed result.

---
Tags: code-golf
---