# Question
Title: Parallel resistance in electric circuits
### Introduction:

Two resistors, `R1` and `R2`, in parallel (denoted `R1 || R2`) have a combined resistance `Rp` given as:

$$R\_{P\_2} = \frac{R\_1\cdot R\_2}{R\_1+R\_2}$$ or as suggested in comments:

$$R\_{P\_2} = \frac{1}{\frac{1}{R\_1} + \frac{1}{R\_2}}$$

Three resistors, `R1`, `R2` and `R3` in parallel (`R1 || R2 || R3`) have a combined resistance `(R1 || R2) || R3 = Rp || R3` :

$$R\_{P\_3} = \frac{\frac{R\_1\cdot R\_2}{R\_1+R\_2}\cdot R\_3}{\frac{R\_1\cdot R\_2}{R\_1+R\_2}+R\_3}$$

or, again as suggested in comments:

$$R\_{P\_3} = \frac{1}{\frac{1}{R\_1} + \frac{1}{R\_2}+ \frac{1}{R\_3}}$$

These formulas can of course be extended to an indefinite number of resistors.

---

### Challenge:

Take a list of positive resistor values as input, and output the combined resistance if they were placed in parallel in an electric circuit. You may not assume a maximum number of resistors (except that your computer can handle it of course).

### Test cases:

```
1, 1
0.5

1, 1, 1
0.3333333

4, 6, 3
1.3333333

20, 14, 18, 8, 2, 12
1.1295

10, 10, 20, 30, 40, 50, 60, 70, 80, 90
2.6117

```

---

**Shortest code in each language wins. Explanations are highly encouraged.**

# Answer
# 05AB1E, ~~5~~ 3 bytes

```
zOz

```

Try it online!

---

### Explanation

```
z                     # compute 1/x for each x in input
 O                    # sum input
  z                   # compute 1/sum

```
> 13 votes

# Answer
# Haskell, ~~18~~ 16 bytes

```
(1/).sum.map(1/)

```

Try it online!
> 11 votes

# Answer
# MATLAB, 14 bytes

In MATLAB `norm(...,p)` computes the `p`-norm of a vector. This is usually defined for \\$p \geqslant 1\\$ as

$$\Vert v \Vert\_p = \left( \sum\_i \vert v\_i \vert^p \right)^{\frac{1}{p}}.$$

But luckily for us, it also happens to work for \\$p=-1\\$. (Note that it does not work in Octave.)

```
@(x)norm(x,-1)

```

Don't try it online!
> 10 votes

# Answer
# Jelly,  ~~5~~  3 bytes

```
İSİ

```

**Try it online!**

### How?

Initially I forgot this form from my electronic engineering days ...how easily we forget.

```
İSİ - Link: list of numbers, R   e.g. [r1, r2, ..., rn]
İ   - inverse (vectorises)            [1/r1, 1/r2, ..., 1/rn]
 S  - sum                             1/r1 + 1/r2 + ... + 1/rn
  İ - inverse                         1/(1/r1 + 1/r2 + ... + 1/rn)

```
> 7 votes

# Answer
# Octave, 15 bytes

```
@(x)1/sum(1./x)

```

Try it online!

Harmonic mean, divided by `n`. Easy peasy.
> 5 votes

# Answer
# PowerShell, 22 bytes

```
$args|%{$y+=1/$_};1/$y

```

Try it online!

Takes input via splatting and uses the same 1/sum of inverse trick as many of the others are doing
> 4 votes

# Answer
# APL (Dyalog Unicode), 4 bytes

```
÷1⊥÷

```

Try it online!

-1 thanks to Adám.
> 4 votes

# Answer
# , 15 bytes

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

```

Try it online!

Follows the same Harmonic Mean principle seen in other answers.
> 3 votes

# Answer
# JavaScript, 28 bytes

```
a=>a.map(y=>x+=1/y,x=0)&&1/x

```

Try it Online!
> 3 votes

# Answer
# Perl 6, 14 bytes

```
1/*.sum o 1/**

```

Try it online!

`1 / **` is an anonymous function that returns a list of the reciprocals of its arguments. `1 / *.sum` is another anonymous function that returns the reciprocal of the sum of the elements of its list argument. The `o` operator composes those two functions.
> 3 votes

# Answer
# Perl 5 `-pa -MList::Util=reduce`, 26 bytes

```
$_=reduce{$a*$b/($a+$b)}@F

```

Try it online!
> 3 votes

# Answer
# bash + coreutils, 25 bytes

```
bc -l<<<"1/(0${@/#/+1/})"

```

TIO
> 3 votes

# Answer
# Wolfram Language (Mathematica), 10 bytes

```
1/Tr[1/#]&

```

Try it online!
> 3 votes

# Answer
# MathGolf, 3 bytes

```
∩Σ∩

```

The same as other answers, using the builtins  (\\$\frac{1}{n}\\$) and `Σ` (sum): $$M(x\_1,...,x\_n)=\frac{1}{\frac{1}{x\_1} + \frac{1}{x\_2} + ... + \frac{1}{x\_n}}$$

Try it online.
> 3 votes

# Answer
# Java 8, 24 bytes

```
a->1/a.map(d->1/d).sum()

```

I noticed there wasn't a Java answer yet, so figured I'd add one.

Try it online.

**Explanation:**

Uses the same Harmonic Mean approach as other answers:

$$M(x\_1,...,x\_n)=\frac{1}{\frac{1}{x\_1} + \frac{1}{x\_2} + ... + \frac{1}{x\_n}}$$

```
a->                       // Method with DoubleStream parameter and double return-type
     a.map(d->1/d)        //  Calculate 1/d for each value `d` in the input-stream
                  .sum()  //  Then take the sum of the mapped list
   1/                     //  And return 1/sum as result

```
> 3 votes

# Answer
# JavaScript (ES6), 29 bytes

```
a=>a.reduce((p,c)=>p*c/(p+c))

```

Try it online!

or:

```
a=>1/a.reduce((p,c)=>p+1/c,0)

```

Try it online!

But with this approach, using `map()` (as Shaggy did) is 1 byte shorter.
> 2 votes

# Answer
# MATL, 5 bytes

```
,1w/s

```

Try it online!

I'm not sure if "do twice" (`,`) counts as a loop, but this is just the harmonic mean, divided by `n`.

Alternately, `,-1^s` is five bytes as well.
> 2 votes

# Answer
# PHP, 51 bytes

Reciprocal of sum of reciprocals. Input is `$a`.

```
1/array_reduce($a,function($c,$i){return$c+1/$i;});

```

Try it online!
> 2 votes

# Answer
# Python 3, 30 bytes

```
lambda r:1/sum(1/v for v in r)

```

**Try it online!**
> 2 votes

# Answer
# Perl 5 (-p), 17 bytes

```
$a+=1/$_}{$_=1/$a

```

Try it online!
> 2 votes

# Answer
# x86-64 Machine code - ~~20~~ 18 bytes

```
0F 57 C0             xorps       xmm0,xmm0
loopHead
F3 0F 53 4C 8A FC    rcpss       xmm1,dword ptr [rdx+rcx*4-4]
0F 58 C1             addps       xmm0,xmm1
E2 F6                loop        loopHead
0F 53 C0             rcpps       xmm0,xmm0
C3                   ret

```

Input - Windows calling convention. First parameter is the number of resistors in `RCX`. A pointer to the resistors is in `RDX`. `*ps` instructions are used since they are one byte smaller. Technically, you can only have around 2^61 resistors but you will be out of RAM long before then. The precision isn't great either, since we are using `rcpps`.
> 2 votes

# Answer
# Intel 8087 FPU machine code, 19 bytes

```
 D9 E8      FLD1                    ; push 1 for top numerator on stack
 D9 EE      FLDZ                    ; push 0 for running sum
        R_LOOP:
 D9 E8      FLD1                    ; push 1 numerator for resistor
 DF 04      FILD WORD PTR[SI]       ; push resistor value onto stack
 DE F9      FDIV                    ; divide 1 / value
 DE C1      FADD                    ; add to running sum
 AD         LODSW                   ; increment SI by 2 bytes
 E2 F4      LOOP R_LOOP             ; keep looping
 DE F9      FDIV                    ; divide 1 / result
 D9 1D      FSTP WORD PTR[DI]       ; store result as float in [DI]

```

This uses the stack-based floating point instructions in the original IBM PC's 8087 FPU.

Input is pointer to resistor values in `[SI]`, number of resistors in `CX`. Output is to a single precision (DD) value at `[DI]`.
> 2 votes

# Answer
# Rattle, 24 bytes

```
|>II^[=1+#g`e_1P+~s]`e_1

```

Try it Online!

This answer can probably be golfed more (can anyone outgolf me in my own language?)

# Explanation

```
|                 take input, parse automatically (Rattle's input parsing is powerful
                   enough to recognise "1,2,3" etc. as a list)
 >                move pointer to the right (to slot 1)
  I               flatten input list and insert into consecutive memory slots
   I^             get length of this list (which is still on top of the stack)
     [ ... ]`     loop structure: loop as many times as the length of the list

=1                set top of stack to 1
  +#              increment top of stack by list's iterator
                   (the number of times the loop has run)
    g`            get the value in storage at the calculated index (iterator + 1)
      e_1         get 1/x of this value
         P        set the pointer to slot 0
          +~      increment the current value by the stored value in slot 0
            s     save the result to slot 0
e_1                get 1/x of this value

```
> 2 votes

# Answer
# Charcoal, 7 bytes

```
Ｉ∕¹Σ∕¹Ａ

```

Try it online! Link is to verbose version of code. Works by calculating the current drawn by each resistor when 1V is applied, taking the total, and calculating the resistance that would draw that current when 1V is applied. Explanation:

```
      Ａ Input array
    ∕¹  Reciprocal (vectorised)
   Σ    Sum
 ∕¹     Reciprocal
Ｉ       Cast to string for implicit print

```
> 1 votes

# Answer
# Dart, 42 bytes

```
f(List<num>a)=>a.reduce((p,e)=>p*e/(p+e));

```

Try it online!

Having to explicitly specify the `num` type is kinda sucky, prevents type infering, because it would infer to `(dynamic, dynamic) => dynamic` which can't yield doubles for some reason
> 1 votes

# Answer
# PHP, 40 bytes

```
for(;$n=$argv[++$i];$r+=1/$n);echo 1/$r;

```

Try it online!

Tests: Try it online!

Similar to Yimin Rong's solution but without built-ins and all program bytes are included in the bytes count.
> 1 votes

# Answer
# Python 3, ~~58~~ 44 bytes

```
f=lambda x,y=0,*i:f(x*y/(x+y),*i)if y else x

```

A recursive function. Requires arguments to be passed unpacked, like so:

```
i=[10, 10, 20]
f(*i)

```

or

```
f(10, 10, 20)

```

**Explanation:**

```
# lambda function with three arguments. *i will take any unpacked arguments past x and y,
# so a call like f(10, 20) is also valid and i will be an empty tuple
# since y has a default value, f(10) is also valid
f=lambda x,y=0,*i: \

# a if case else b
# determine parallel resistance of x and y and use it as variable x
# since i is passed unpacked, the first item in the remaining list will be y and
# the rest of the items will be stored in i
# in the case where there were no items in the list, y will have the default value of 0
f(x*y/(x+y),*i) \

# if y does not exist or is zero, return x
if y else x

```
> 1 votes

# Answer
# , 6 bytes

```
1%1#.%

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~26~~ 22 bytes

-4 bytes thanks to @ValueInk.

```
->x{1/x.sum{|i|1.0/i}}

```

Try it online!
> 1 votes

# Answer
# \[MATLAB\], 15 bytes

One more byte than *flawr* excellent answer, but I had to use other functions so here goes:

```
@(x)1/sum(1./x)

```

It's rather explicit, it sums the inverse of the resistances, then invert the sum to output the equivalent parallel resistance.
> 1 votes

# Answer
# Forth (gforth), 49 bytes

```
: f 0e 0 do dup i cells + @ s>f 1/f f+ loop 1/f ;

```

Try it online!

Input is a memory address and array length (used as an impromptu array, since Forth doesn't have a built-in array construct)

Uses the sum-of-inverse method as most other answers are

### Code Explanation

```
: f           \ start a new word definition
  0e          \ stick an accumulator on the floating point stack
  0 do        \ start a loop from 0 to array-length -1
    dup       \ copy the array address
    i cells + \ get the address of the current array value
    @ s>f     \ get the value and convert it to a float
    1/f f+    \ invert and add to accumulator
  loop        \ end the loop definition
  1/f         \ invert the resulting sum
;             \ end the word definition

```
> 1 votes

# Answer
## C#, 16 bytes

```
1/l.Sum(n=>1f/n)

```

## Try It
> 1 votes

# Answer
# expl3 (LaTeX3 programming layer), 65 bytes

The following defines a function that prints the result to the terminal (unfortunately `expl3` has very verbose function names):

```
\def\1#1{\fp_show:n{1/(\clist_map_function:nN{#1}\2)}}\def\2{+1/}

```

A complete script which can be run from the terminal including all the test cases as well as the setup to enter `expl3`:

```
\RequirePackage{expl3}\ExplSyntaxOn
\def\1#1{\fp_show:n{1/(\clist_map_function:nN{#1}\2)}}\def\2{+1/}
\1{1, 1}
\1{1, 1, 1}
\1{4, 6, 3}
\1{20, 14, 18, 8, 2, 12}
\1{10, 10, 20, 30, 40, 50, 60, 70, 80, 90}
\stop

```

If run with `pdflatex <filename>` the following is the console output:

```
This is pdfTeX, Version 3.14159265-2.6-1.40.20 (TeX Live 2019) (preloaded format=pdflatex)
 restricted \write18 enabled.
entering extended mode
(./cg_resistance.tex
LaTeX2e <2018-12-01>
(/usr/local/texlive/2019/texmf-dist/tex/latex/unravel/unravel.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3kernel/expl3.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3kernel/expl3-code.tex)
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3backend/l3backend-pdfmode.def))
 (/usr/local/texlive/2019/texmf-dist/tex/latex/l3packages/xparse/xparse.sty)
(/usr/local/texlive/2019/texmf-dist/tex/generic/gtl/gtl.sty))
> 1/(\clist_map_function:nN {1,1}\2)=0.5.
<recently read> }

l.3 \1{1, 1}

?
> 1/(\clist_map_function:nN {1,1,1}\2)=0.3333333333333333.
<recently read> }

l.4 \1{1, 1, 1}

?
> 1/(\clist_map_function:nN {4,6,3}\2)=1.333333333333333.
<recently read> }

l.5 \1{4, 6, 3}

?
> 1/(\clist_map_function:nN {20,14,18,8,2,12}\2)=1.129538323621694.
<recently read> }

l.6 \1{20, 14, 18, 8, 2, 12}

?
> 1/(\clist_map_function:nN
{10,10,20,30,40,50,60,70,80,90}\2)=2.611669603067675.
<recently read> }

l.7 \1{10, 10, 20, 30, 40, 50, 60, 70, 80, 90}

?
 )
No pages of output.
Transcript written on cg_resistance.log.

```

## Explanation

`\fp_show:n` : evaluates its argument as a floating point expression and prints the result on the terminal, every expandable macro is expanded during that process.

`\clist_map_function:nN` : takes two arguments, a comma separated list and a function/macro, if called like `\clist_map_function:nN { l1, l2, l3 } \foo` it expands to something like `\foo{l1}\foo{l2}\foo{l3}`. In our case instead of `\foo` the macro `\2` is used, which expands to `+1/` so that the expression expands to `+1/{l1}+1/{l2}+1/{l3}`
> 1 votes

# Answer
# SimpleTemplate, 72 bytes

Okay, this was VERY hard!
Specifically with a language that has VERY poor math support.

```
{@fnx A,S}{@eachA}{@set/_ 1 _}{@set+S S,_}{@/}{@set/S 1 S}{@returnS}{@/}

```

Creates a function `x` that *must* be called by passing an array as the first and only argument.

**Ungolfed**:

```
{@fn calc values, sum}
    {@each values as value}
        {@set/ value 1 value}
        {@set+ sum sum, value}
    {@/}
    {@set/ sum 1 sum}
    {@return sum}
{@/}

```

**Explanation**:

* `{@fn calc values, sum}` \- Creates the function `calc`, which has 2 variables (`values` and `sum`) taking the values of the first arguments (defaults to `null`)
* `{@each values as value}` \- Loops over each `value` in `values`
* `{@set/ value 1 value}` \- Divides `1` by `value`, storing it into `value`
* `{@set+ sum sum, value}` \- Adds `sum` to `value`, storing it into `sum`
* `{@/}` \- Closes the `{@each}` (usually optional)
* `{@set/ sum 1 sum}` \- Divides `1` by `sum`, storing it into `sum`
* `{@return sum}` \- Returns `sum` (duh)
* `{@/}` \- Closes the `{@fn}` (usually optional, even if it shouldn't be for functions)

To use the function, you can use this code:

```
{@set values 10, 10, 20, 30, 40, 50, 60, 70, 80, 90} {@//array of values}
{@call calc into result values}
{@echo result} {@//2.6116696030677}

```

---

---

If you are curious, the ungolfed example compiles to this PHP code:

```
// {@fn calc values, sum}
$DATA['calc'] = function()use(&$FN, &$_){
    $DATA = array(
        'argv' => func_get_args(),
        'argc' => func_num_args(),
        'VERSION' => '0.62',
        'EOL' => PHP_EOL,
        'PARENT' => &$_
    );
    $_ = &$DATA;
    $DATA["values"] = &$DATA["argv"][0];
    $DATA["sum"] = &$DATA["argv"][1];

    // {@each values as value}
    // loop variables
    $tmp_1_val = isset($DATA['values']) ? $tmp_1_val = &$DATA['values'] : null;
    $tmp_1_keys = gettype($DATA['values']) == 'array'
        ? array_keys($DATA['values'])
        : array_keys(range(0, strlen($tmp_1_val = $tmp_1_val . '') - 1));
    $tmp_1_key_last = end($tmp_1_keys);

    // loop
    foreach($tmp_1_keys as $tmp_1_index => $tmp_1_key){
        $DATA['loop'] = array(
            'index' => $tmp_1_index,
            'i' => $tmp_1_index,
            'key' => $tmp_1_key,
            'k' => $tmp_1_key,
            'value' => $tmp_1_val[$tmp_1_key],
            'v' => $tmp_1_val[$tmp_1_key],
            'first' => $tmp_1_key === $tmp_1_keys[0],
            'last' => $tmp_1_key === $tmp_1_key_last,
        );
        $DATA['__'] = $tmp_1_key;
        $DATA['value'] = $tmp_1_val[$tmp_1_key];

        // {@set/ value 1 value}
        $DATA['value'] = array_map(function($value)use(&$DATA){return (1 / $value);}, $FN['array_flat']((isset($DATA['value'])?$DATA['value']:null)));

        // {@set+ sum sum, value}
        $DATA['sum'] = array_sum($FN['array_flat'](array((isset($DATA['sum'])?$DATA['sum']:null),(isset($DATA['value'])?$DATA['value']:null))));

    // {@/}
    };

    // {@set/ sum 1 sum}
    $DATA['sum'] = array_map(function($value)use(&$DATA){return (1 / $value);}, $FN['array_flat']((isset($DATA['sum'])?$DATA['sum']:null)));

    // {@return sum}
    return (isset($DATA['sum'])?$DATA['sum']:null);

// {@/}
};

// {@set values 10, 10, 20, 30, 40, 50, 60, 70, 80, 90}
$DATA['values'] = array(10,10,20,30,40,50,60,70,80,90);

// {@call calc into result values}
$DATA['result'] = call_user_func_array(isset($DATA['calc']) && is_callable($DATA['calc'])? $DATA['calc']: (isset($FN["calc"])? $FN["calc"]: "calc"), array((isset($DATA['values'])?$DATA['values']:null)));

// {@echo result}
echo implode('', $FN['array_flat']((isset($DATA['result'])?$DATA['result']:null)));

```
> 1 votes

# Answer
# Vyxal `d`, 3 bytes

```
Ė∑Ė

```

Try it Online!

Reciprocal, sum, reciprocal.

You can remove `d` if you're fine with the result being double-wrapped in a list for some reason.
> 1 votes

# Answer
# Pyth, 6 bytes

```
c1scL1

```

Try it online!

Uses the modified formula \\$\frac{1}{R\_P}=\frac{1}{R\_1} + \frac{1}{R\_2}\\$.

```
c1      # 1/
  s     #   sum(                     )
   cL1  #       map(lambda x: 1/x, Q)  # Q (=input) is implicit

```
> 0 votes

# Answer
# Japt v2.0a0, 7 bytes

```
1÷Ux!÷1

```

Try it
> 0 votes

# Answer
# OCaml, 50 bytes

```
fun l->1./.(List.fold_left(fun a e->a+.1./.e)0. l)

```

Try it online!
> 0 votes

# Answer
# Stax, 5 bytes

```
{u+Fu

```

Run and debug it at staxlang.xyz!

```
{  F     For each:
 u         Invert
  +        Add to running total
    u    Invert
         Implicit print as fraction

```
> 0 votes

# Answer
# Scala, 15 bytes

```
1/_.map(1/).sum

```

Try it online!
> 0 votes

# Answer
# Python, 30 bytes

```
lambda v:1/sum(1/x for x in v)

```

-2, thanks @JoKing
> 0 votes

# Answer
# jq, 16 characters

```
1/(map(1/.)|add)

```

Sample run:

```
bash-5.0$ jq '1/(map(1/.)|add)' <<< '[10, 10, 20, 30, 40, 50, 60, 70, 80, 90]'
2.611669603067675

```

Try it online!
> 0 votes

# Answer
# C (gcc), ~~65~~ 62 bytes

Thanks to ceilingcat for -3 bytes.

```
float a(b,c)int*b;{float d=0;for(;c--;)d+=1./b[c];return 1/d;}

```

Try it online!
> 0 votes

# Answer
# C++ (clang), 78 bytes

```
#import<list>
void f(std::list<int>r,double&s){s=0;for(int p:r)s+=1./p;s=1/s;}

```

Try it online!
> 0 votes

# Answer
# Pyt, 3 bytes

```
⅟Ʃ⅟

```

Try it online!

```
⅟        implicit input; take reciprocal
 Ʃ       sum
  ⅟      take reciprocal; implicit print

```
> 0 votes

# Answer
# Thunno, \\$ 3 \log\_{256}(96) \approx \\$ 2.47 bytes

```
oSo

```

Attempt This Online!

#### Explanation

```
oSo  # Implicit input
o    # Inverse: 1 / input
 S   # Sum this list
  o  # Inverse: 1 / sum
     # Implicit output

```
> 0 votes

# Answer
# JavaScript (Node.js), 27 bytes

```
a=>1/eval('1/'+a.join`+1/`)

```

Try it online!
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
ỊSỊ

```

Try it online!

#### Explanation

```
ỊSỊ  # Implicit input
Ị    # Reciprocal
 S   # Sum
  Ị  # Reciprocal
     # Implicit output

```
> 0 votes

---
Tags: code-golf, math, physics, electrical-engineering
---


title: Replace twos with threes

text:
# Question
Title: Replace twos with threes
Given a positive integer n write some code to take its prime factorization and replace all of its factors of `2` with `3`.

For example

```
12 = 2 * 2 * 3 -> 3 * 3 * 3 = 27

```

This is so the goal is to minimize the byte count of your answer.

# Test cases

```
1 -> 1
2 -> 3
3 -> 3
4 -> 9
5 -> 5
6 -> 9
7 -> 7
8 -> 27
9 -> 9
10 -> 15
11 -> 11
12 -> 27
13 -> 13
14 -> 21
15 -> 15
16 -> 81
17 -> 17
18 -> 27
19 -> 19
20 -> 45
21 -> 21
22 -> 33
23 -> 23
24 -> 81
25 -> 25
26 -> 39
27 -> 27
28 -> 63
29 -> 29

```

# Answer
> 71 votes
# Fractran, 3 bytes

```
3/2

```

Fractran literally only has one builtin, but it happens to do exactly what this task is asking for. (It's also Turing-complete, by itself.)

The language doesn't really have a standardised syntax or interpreter. This interpreter (in a comment to a blog post – it's a very simple language) will accept the syntax shown here. (There are other Fractran interpreters with other syntaxes, e.g. some would write this program as `3 2`, or even using `3` and `2` as command line arguments, which would lead to a score of 0+3 bytes. I doubt it's possible to do better than 3 in a pre-existing interpreter, though.)

## Explanation

```
3/2
 /   Replace a factor of
  2  2
3    with 3
     {implicit: repeat until no more replacements are possible}

```

# Answer
> 24 votes
# Python 2, 28 bytes

```
f=lambda n:n%2*n or 3*f(n/2)

```

Try it online!

Recursively divide the number by 2 and multiplies the result by 3, as long as the number is even. Odd numbers return themselves.

**32 byte alt:**

```
lambda n:n*(n&-n)**0.58496250072

```

Try it online. Has some float error. The constant is `log_2(3)-1`.

Uses `(n&-n)` to find the greatest power-of-2 factor of `n`, the converts `3**k` to `2**k` by raising it to the power of `log_2(3)-1`.

# Answer
> 19 votes
# 05AB1E, 4 bytes

```
Ò1~P

```

Try it online!

### How it works

```
Ò     Compute the prime factorization of the input.
 1~   Perform bitwise OR with 1, making the only even prime (2) odd (3).
   P  Take the product of the result.

```

# Answer
> 14 votes
## Haskell, ~~24~~ 23 bytes

```
until odd$(*3).(`div`2)

```

The divide by two and multiply by 3 until odd trick in Haskell.

Try it online!

Alternative with a lambda instead of a pointfree function and with the same byte count:

```
odd`until`\x->div(x*3)2

```

Edit: @ais523 saved a byte in the original version and @Ørjan Johansen one in the alternative version, so both version have still the same length. Thanks!

# Answer
> 8 votes
## JavaScript (ES6), 19 bytes

```
f=x=>x%2?x:f(x*1.5)

```

While the input is divisible by two, multiplies it by 1.5, which is equivalent to dividing by 2 and multiplying by 3.

# Answer
> 8 votes
# Brain-Flak, 76 bytes

```
{{({}[()]<([({})]()<({}{})>)>)}{}([{}]()){{}((({})){}{})<>}<>}<>({}({}){}())

```

Try it online!

## Explanation

This program works by dividing the number by two and tripling until it gets a remainder of one from the division. Then it stops looping and doubles and adds one to the final number.

### More detailed explanation eventually...

# Answer
> 7 votes
# Mathematica, ~~22~~ 19 bytes

*Thanks to lanlock4 for saving 3 bytes!*

```
#//.x_?EvenQ:>3x/2&

```

Pure function that does the replacement repeatedly, one factor of 2 at a time. Works on all positive integers less than 265537.

# Answer
> 6 votes
# Perl 6, 14 bytes

```
{1.5**.lsb*$_}

```

lsb returns the position of the least-significant bit, counted from the right. That is, how many trailing zeroes in the binary representation, which is the same as the number of factors of 2. So raise 3/2 to that power and we're done.

```
say {$_*1.5**.lsb}(24);
> 81

```

# Answer
> 6 votes
# Lean, ~~139~~ ~~82~~ 71 bytes

*11 bytes saved by ovs.*

```
import data.nat.prime
open list
λx,prod$map(λp,p+1-p%2)$nat.factors x

```

Try it online!

I'm really new to lean so, this answer is probably really inefficient in ways I don't yet know. But it works.

We get a list of factors with `nat.factors` replace `2`s with threes using a `map` and roll it back up with `list.prod`.

# Answer
> 5 votes
# 05AB1E, ~~6~~ 5 bytes

Saved a byte thanks to *Adnan*.

```
ÒDÈ+P

```

Try it online!

**Explanation**

```
Ò       # push list of prime factors of input
 D      # duplicate
  È     # check each factor for evenness (1 if true, else 0)
   +    # add list of factors and list of comparison results
    P   # product

```

# Answer
> 5 votes
# MATL, ~~7~~, 6 bytes

```
Yf1Z|p

```

Try it online!

*1 byte saved thanks to Dennis's genius observation*

---

The best way to explain this is to show the stack at various points.

```
Yf  % Prime factors

[2 2 2 3]

1Z| % Bitwise OR with 1

[3 3 3 3]

p   % Product

81

```

Alternate solution:

```
Yfto~+p

```

# Answer
> 5 votes
## Alice, 9 bytes

```
2/S 3
o@i

```

Try it online!

Alice has a built-in to replace a divisor of a number with another. I didn't think I'd actually get to make use of it so soon...

Using the code points of characters for I/O, this becomes 6 bytes: `I23SO@`.

### Explanation

```
2   Push 2 (irrelevant).
/   Reflect to SE. Switch to Ordinal.
i   Read all input as a string.
    The IP bounces up and down, hits the bottom right corner and turns around,
    bounces down again.
i   Try to read more input, but we're at EOF so this pushes an empty string.
/   Reflect to W. Switch to Cardinal.
2   Push 2.
    The IP wraps around to the last column.
3   Push 3.
S   Implicitly discard the empty string and convert the input string to the integer
    value it contains. Then replace the divisor 2 with the divisor 3 in the input.
    This works by multiplying the value by 3/2 as long as it's divisible by 2.
/   Reflect to NW. Switch to Ordinal.
    Immediately bounce off the top boundary. Move SW.
o   Implicitly convert the result to a string and print it.
    Bounce off the bottom left corner. Move NE.
/   Reflect to S. Switch to Cardinal.
@   Terminate the program.

```

# Answer
> 5 votes
# Java, 38 bytes

```
int f(int n){return n%2>0?n:f(n/2*3);}

```

Try it online!

---

Previous 43-byte solution:

```
int f(int n){for(;n%2<1;)n=n/2*3;return n;}

```

Try it online!

# Answer
> 5 votes
# Hexagony, ~~112~~ 91 bytes

Grid size 6 (91 bytes)

```
      ? { 2 . . <
     / = { * = \ "
    . & . . . { _ '
   . . { . . } ' * 2
  _ } { / . } & . ! "
 . > % . . < | . . @ |
  \ . . \ . | ~ . . 3
   . . " . } . " . "
    . & . \ = & / 1
     \ = { : = } .
      [ = { { { <

```

Compact version

```
?{2..</={*=\".&...{_'..{..}'*2_}{/.}&.!".>%..<|..@|\..\.|~..3..".}.".".&.\=&/1\={:=}.[={{{<

```

Grid size 7 (112 bytes)

```
       ? { 2 " ' 2 <
      / { * \ / : \ "
     . = . = . = | . 3
    / & / { . . } { . "
   . > $ } { { } / = . 1
  _ . . } . . _ . . & . {
 . > % < . . ~ & . . " . |
  | . . } - " . ' . @ | {
   . . . = & . . * ! . {
    . . . _ . . . _ . =
     > 1 . . . . . < [
      . . . . . . . .
       . . . . . . .

```

Try it online!

Compact Version:

```
?{2"'2</{*\/:\".=.=.=|.3/&/{..}{.".>$}{{}/=.1_..}.._..&.{.>%<..~&..".||..}-".'.@|{...=&..*!.{..._..._.=>1.....<[

```

Ungolfed Version for better readability:

Approximate Memory Layout

Grey Path (Memory initialization)

```
?     Read input as integer (Input)
{     Move to memory edge "Divisor left"
2     Set current memory edge to 2
" '   Move to memory edge "Divisor right"
2     Set current memory edge to 2
"     Move to memory edge "Multiplier"
3     Set current memory edge to 3
"     Move to memory edge "Temp 2"
1     Set current memory edge to 1
{ { { Move to memory edge "Modulo"
=     Turn memory pointer around
[     Continue with next instruction pointer

```

Loop entry

```
%     Set "Modulo" to Input mod Divisor
<     Branch depending on result

```

Green Path (value is still divisible by 2)

```
} } {     Move to memory edge "Result"
=         Turn memory pointer around
*         Set "Result" to "Temp 2" times "Multiplier" (3)
{ = &     Copy "Result" into "Temp2"
{ { } } = Move to "Temp"
:         Set "Temp" to Input / Divisor (2)
{ = &     Copy "Temp" back to "Input"
"         Move back to "Modulo"

```

Red Path (value is no longer divisible by 2)

```
} = & " ~ & ' Drag what's left of "Input" along to "Multiplier"
*             Multiply "Multiplier" with "Temp 2"
! @           Output result, exit program

```

# Answer
> 4 votes
# Jelly, ~~8~~ 5 bytes

```
Æf3»P

Æf3»P  Main Link, argument is z
Æf     Prime factors
  3»   Takes maximum of 3 and the value for each value in the array
    P  Takes the product of the whole thing

```

Try it online!

-3 bytes thanks to a hint from @Dennis!

# Answer
> 4 votes
# Retina, 23 bytes

```
.+
$*
+`^(1+)\1$
$&$1
1

```

Try it online! Link is to test suite that runs automatically runs all inputs from 1 to 29. Explanation:

```
.+
$*

```

Convert to unary.

```
+`^(1+)\1$
$&$1

```

While the value is even, multiply it by `3/2`.

```
1

```

Convert to decimal.

Note that any FRACTRAN program is trivially convertible to a Retina program with unary I/O. The fraction itself is converted into a match for a string that appears an exact number of times given by the denominator, and the substitution is then `$1` repeated a number of times given by the numerator, although if this is greater than the denominator then `$&` can be used to golf down the code length. It then remains to loop each fraction back to the start of the script, so that the earliest possible fraction is always the next to be substituted. In the case of a single fraction no group is required of course.

# Answer
> 4 votes
# Brachylog, 7 bytes

```
~×₂×₃↰|

```

Try it online!

## How it works

```
~×₂×₃↰|      original program
?~×₂×₃↰.|?.  with implicit input (?) and output (.) added

?~×₂         input "un-multiplied" by 2
    ×₃       multiplied by 3
      ↰      recursion
       .     is the output
        |    or (in case the above fails, meaning that the input
                 cannot be "un-multiplied" by 2)
         ?.  the input is the output

```

# Answer
> 4 votes
# Hexagony, ~~28 27~~ 26 bytes

```
?'2{{(\}}>='!:@=$\%<..>)"*

```

Try it online!

Laid out:

```
    ? ' 2 {
   { ( \ } }
  > = ' ! : @
 = $ \ % < . .
  > ) " * . .
   . . . . .
    . . . .

```

This basically runs:

```
num = input()
while num%2 == 0:
    num = (num/2)*3
print num

```

At this point it's an exercise on how torturous I can get the loop path to minimise bytes.

# Answer
> 3 votes
# Pyth - ~~14~~ ~~10~~ 9 bytes

```
*^1.5/PQ2

```

Counts the number of 2s in the prime factorization (/PQ2). Multiplies the input by 1.5^(# of 2s)

Try it

# Answer
> 3 votes
# Risky, 9 bytes

```
*\?+0+0+0__?\?+?:2

```

Try it online!

# Answer
> 3 votes
# BQN (CBQN), 30 bytes

```
{0=2|?3×÷2;}
```

Attempt This Online!

# Answer
> 2 votes
# , ~~15~~ ~~12~~ 10 bytes

```
(+2&=)&.q:

```

Try it online! Works similar to below, just has different logic concerning replacement of `2` with `3`.

# 15 bytes

```
(2&={,&3)"+&.q:

```

Try it online!

## Explanation

```
(2&={,&3)"+&.q:
           &.    "under"; applies the verb on the right, then the left,
                 then the inverse of the right
             q:  prime factors
(       )"+      apply inside on each factor
     ,&3         pair with three: [factor, 3]
 2&=             equality with two: factor == 2
    {            list selection: [factor, 3][factor == 2]
                 gives us 3 for 2 and factor for anything else
           &.q:  under prime factor

```

# Answer
> 2 votes
# , 11 bytes

```
[:*/q:+2=q:

```

Try it online!

`[:` cap (placeholder to call the next verb monadically)

`*/` the product of

`q:` the prime factors

`+` plus (i.e. with one added where)

`2` two

`=` is equal to (each of)

`q:` the prime factors

# Answer
> 2 votes
# PHP, 36 Bytes

```
for($a=$argn;$a%2<1;)$a*=3/2;echo$a;

```

Try it online!

# Answer
> 2 votes
## CJam, ~~10~~ 9 bytes

```
rimf1f|:*

```

Really simple.

Explanation:

```
ri  e# Read integer:         | 28
mf  e# Prime factors:        | [2 2 7]
1   e# Push 1:               | [2 2 7] 1
f|  e# Bitwise OR with each: | [3 3 7]
:*  e# Product:              | 63

```

# Answer
> 1 votes
# Japt, ~~19 16 10 9~~ 7 bytes

```
k ®w3Ã×

```

Try it online!

# Explanation

```
 k ®   w3Ã ×
Uk mZ{Zw3} r*1
U              # (input)
 k m           # for every prime factor
    Z{Zw3}     # replace it by the maximum of itself and 3
           r*1 # output the product

```

# Answer
> 1 votes
# Japt, 7 bytes

```
k mw3 ×

```

Try it online!

### Explanation

```
k mw3 ×

k        // Factorize the input.
  mw3    // Map each item X by taking max(X, 3).
      ×  // Take the product of the resulting array.
         // Implicit: output result of last expression

```

# Answer
> 1 votes
# Pyth, 9 bytes

Integer output \o/

```
*F+1.|R1P

```

Test suite.

## How it works

```
*F+1.|R1P
        P   prime factorization
    .|R1    bitwise OR each element with 1
*F+1        product

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 26 bytes

```
{⍵(⊣×(3*⊢)×(÷2*⊢))2⍟⍵∨2*⍵}

```

Try it online!

This is too verbose, I must be doing something wrong...

# Answer
> 1 votes
# R, 42 bytes

The only right amount of bytes in an answer.

```
x=gmp::factorize(scan());x[x==2]=3;prod(x)

```

Pretty straightforward, uses the `gmp` package to factorize `x`, replaces 2s by 3s, and returns the product.

# Answer
> 1 votes
# Befunge-93, 20 bytes

```
&>:2%!#v_.@
 ^*3/2 <

```

Try it online!

```
& - take in input and add it to the stack
> - move right
: - duplicate the top of the stack
2 - add two to the stack
% - pop 2 and the input off the stack and put input%2 on the stack
! - logical not the top of the stack
# - jump over the next command
_ - horizontal if, if the top of the stack is 0 (i.e. input%2 was non zero) go
    right, else go left

If Zero:
. - output the top of the stack
@ - end code

If Not Zero:
v - move down
< - move left
2 - add 2 the top of the stack
/ - pop top two, add var/2 to the stack
3 - add 3 to stack
* - pop top two, add var*3 to the stack
^ - move up
> - move right (and start to loop)

```

# Answer
> 1 votes
# Ruby, 23 bytes

```
f=->n{n%2<1?f[n/2*3]:n}

```

Try it online!

A recursive lambda, nothing shocking.

# Answer
> 1 votes
# Vyxal, 5 bytes

```
ǐ3v∴Π

```

Try it Online!

```
ǐ    # Prime factors
  v∴ # Take max of each and...
 3   # 3
Π    # Take product

```

# Answer
> 1 votes
# tinylisp, 47 bytes

```
(load library
(d F(q((N)(i(odd? N)N(F(*(/ N 2)3

```

Defines a function `F` that takes an integer and returns an integer. Try it online!

### Ungolfed/explanation

The best part is, this uses tail recursion, so it works for arbitrarily large numbers (though it does get horrifically slow).

```
(load library)   ; The library defines the odd?, *, and / functions

(def F           ; Define F to be
 (q              ; a list representing a function
  ((N)           ; that takes one argument, N:
   (if (odd? N)  ; If N is odd
    N            ; just return it
    (F           ; else call F recursively on
     (*          ; the product of
      (/ N 2)    ; N divided by 2
      3))))))    ; with 3

```

# Answer
> 1 votes
# Taxi, 1243 bytes

```
Go to Post Office:W 1 L 1 R 1 L.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:S 1 L 1 R.Pickup a passenger going to Cyclone.Go to Cyclone:N 5 L 2 L.[A]Pickup a passenger going to Narrow Path Park.Pickup a passenger going to Divide and Conquer.2 is waiting at Starchild Numerology.Go to Starchild Numerology:N 1 R 3 L.Pickup a passenger going to Divide and Conquer.Go to Zoom Zoom:W 1 R 3 R.Go to Narrow Path Park:W 1 L 1 L 1 R.Go to Divide and Conquer:E 1 R 2 R.Pickup a passenger going to Cyclone.Go to Cyclone:E 1 L 1 L 2 L.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Trunkers.Go to Trunkers:S 1 L.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:W 1 L.Switch to plan B if no one is waiting.Pickup a passenger going to Multiplication Station.3 is waiting at Starchild Numerology.Go to Starchild Numerology:N 1 R.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:W 1 R 2 R 1 R 4 L.Pickup a passenger going to Cyclone.Go to Cyclone:S 1 R 2 L 2 R.Switch to plan A.[B]Go to Narrow Path Park:N 4 R 1 R 1 L 1 R.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:E 1 R.Pickup a passenger going to Post Office.Go to Post Office:N 1 L 1 R.

```

Try it online!

# Answer
> 1 votes
# Vyxal, 4 bytes

```
ǐ1⋎Π

```

Try it Online!

## How?

```
ǐ1⋎Π
ǐ    # Prime factors
 1⋎  # Bitwise OR each with one
   Π # Product

```

# Answer
> 1 votes
# Factor \+ `math.primes.factors math.unicode`, 28 bytes

```
[ factors """"replace Π ]

```

Try it online!

Note the strings have literal control characters '2' and '3' embedded in them (you can see them on TIO).

# Answer
> 1 votes
# Desmos, 29 bytes

```
f(n)=1.5^{log_2(gcd(n,2^n))}n

```

A surprisingly short solution, and an interesting usage of \\$\operatorname{gcd}()\\$.

Try It On Desmos!

Try It On Desmos! - Prettified

It only works for numbers up to 1024 though. Here is a version that should support significantly more numbers at the cost of a few bytes:

### 42 bytes

```
f(n)=1.5^{log_2(gcd(n,2^{ceil(log_2n)}))}n

```

# Answer
> 1 votes
# Thunno 2, 5 bytes

```
f1Æ|p

```

Try it online!

#### Explanation

```
f1Æ|p  # Implicit input
f      # Prime factorisation
 1Æ|   # Bitwise OR with 1
    p  # Product of the list
       # Implicit output

```

# Answer
> 0 votes
# Pyke, 5 bytes

```
P1.|B

```

Try it online!

# Answer
> 0 votes
# Actually, 9 bytes

```
w⌠i1|ⁿ⌡Mπ

```

Try it online!

Explanation:

```
w⌠i1|ⁿ⌡Mπ
w          factor into [prime, exponent] pairs
 ⌠i1|ⁿ⌡M   for each pair:
  i          flatten
   1|        prime | 1 (bitwise OR)
     ⁿ       raise to exponent
        π  product

```

# Answer
> 0 votes
# Pari/GP, 23 bytes

```
f(n)=if(n%2,n,f(3*n/2))

```

Try it online!

---

# Pari/GP, 23 bytes

```
n->n*1.5^valuation(n,2)

```

Try it online!

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

```
f(n){n=n&1?n:f(n/2*3);}

```

Try it online!

# Answer
> 0 votes
# Chip `-z`, 123 bytes

```
tv~S
a^v.bv.cv.dv.ev.fv.gv.
 zLxzLxzLxzLxzLxzLxzLxz-vh
A##L##L##L##L##L##L##L##'
B))L))L))L))L))L))L))'
   C  D  E  F  G  H

```

Try it online! (Includes a bashy wrapper for numeric conversion).

### Explanation

This solution uses Chip's 'native' data type, an unsigned 8-bit integer. Any input or output that would be outside the bounds of that type will produce undefined results.

I and O are done via raw bytes values, hence the wrapper in the TIO.

The algorithm, in C-ish looks something like this:

```
uchar byte = in();
while(!(byte & 0x1)) {
  byte += byte>>1; // logical shift
}
out(byte);

```

The bulk of this program are the eight full adders (`##`) and their wiring (`L`, `)`, `x`, ...).

To see all steps of the computation, delete the `S`. You may want to adjust the hexdump format to `"%d\n"` for nicer output.

# Answer
> 0 votes
# , 34 bytes

```
function(x){while(!x%%2)x=x/2*3;x}

```

Try it online!

**Or: recursive version** (same bytes)

```
f=function(x)`if`(x%%2,x,f(x/2*3))

```

Try it online!

2 is the only even prime number, so we divide the input by 2 and multiply by 3 until it's no longer even.

---

*Edit: now reading the other answers, this approach has already been used many times in other languages...*

# Answer
> 0 votes
# Assembly (NASM, 32-bit, Linux), 57 bytes

```
mov ebx,3
l:mul ebx
rcr eax,1
jnc l
rcl eax,1
div ebx
ret

```

Try it online!

Both, the input and the output are in the `eax` register.

# Answer
> 0 votes
# MMIX, 20 bytes (5 instrs)

```
00000000: 4e000004 3f000001 1b000003 4f00fffe  N¡¡¥?¡¡¢ñ¡¡¤O¡”“
00000010: f8010000                             ẏ¢¡¡

```

```
r23 BEV  $0,1F      // if(!(i & 1)) goto end
0H  SRU  $0,$0,1    // loop: i >>= 1
    MULU $0,$0,3    // i *= 3
    BEV  $0,0B      // if(!(i & 1)) goto loop
1H  POP  1,0        // return i

```

If it could be guaranteed the number was even, it could be cut down to four instructions (the first instruction is just to avoid halving if already odd).

---
Tags: code-golf, arithmetic, number-theory
---


title: Sum of primes between given range

text:
# Question
Title: Sum of primes between given range
Write the shortest code for finding the sum of primes between \\$a\\$ and \\$b\\$ (inclusive).

**Input**

1. \\$a\\$ and \\$b\\$ can be taken from command line or stdin (space seperated)
2. Assume \\$1 \le a \le b \le 10^8\\$

**Output** Just print the sum with a newline character.

**Bonus Points**

1. If the program accepts multiple ranges (print one sum on each line), you get extra points. :)

# Answer
> 15 votes
# J,41 32 19 characters:

*Update*

(simple sieve)

```
g=:+/@(*1&p:)@-.&i.

```

e.g.

```
100 g 1
1060
250000x g 48
2623030823

```

*Previous*

```
h=:3 :'+/p:i.(_1 p:>:y)'
f=:-&h<:

```

eg:

```
100 f 1
1060

```

# Answer
> 11 votes
## Mathematica 7 (31 chars in plain text)

If PARI/GP solution allowed, then:

```
Plus@@Select[Range[a,b],PrimeQ]

```

# Answer
> 6 votes
# C#, 294 characters

```
using System;class P{static void Main(){int a=int.Parse(Console.ReadLine()),b=int.Parse(Console.ReadLine());long t=0;for(int i=a;i<=b;i++)if(p(i))t+=i;Console.WriteLine(t);}static bool p(int n){if((n%2<1&&n!=2)||n<2)return 0>1;for(int i=3;i<=Math.Sqrt(n);i+=2)if(n%i==0)return 0>1;return 1>0;}}

```

# Answer
> 6 votes
# C, 117 bytes

```
main(a,b,s,j){
s=0,scanf("%d%d",&a,&b);
for(a+=a==1;a<=b;a++)
for(s+=a,j=2;j<a;)
s-=a%j++?0:(j=a);
printf("%d",s);
}

```

# Answer
> 5 votes
# C#, 183 characters

```
using System;class P{static void Main(string[] a){long s=0,i=Math.Max(int.Parse(a[0]),2),j;for(;i<=int.Parse(a[1]);s+=i++)for(j=2;j<i;)if(i%j++==0){s-=i;break;}Console.WriteLine(s);}}

```

This would be much shorter if it didn't have to check for 1, or if there was a better way to... In a more readable format:

```
using System;
class P
{
    static void Main(string[] a)
    {
        long s = 0,
             i = Math.Max(int.Parse(a[0]),2),
             j;

        for (; i <= int.Parse(a[1]);s+=i++)
            for (j = 2; j < i; )
                if (i % j++ == 0)
                {
                    s -= i;
                    break;
                }

        Console.WriteLine(s);
    }
}

```

# Answer
> 4 votes
# PARI/GP, 44 characters

```
sum(x=nextprime(a),precprime(b),x*isprime(x))

```

# Answer
> 4 votes
# BASH Shell, 47 Characters

```
seq 1 100|factor|awk 'NF==2{s+=$2}END{print s}'

```

Edit: Just realized the sum overflows and is coerced as a double.

### 52 50 Characters

Here's a bit longer solution, but handles overflows aswell
```
seq 1 100|factor|awk NF==2{print\$2}|paste -sd+|bc

```

# Answer
> 4 votes
## Haskell (80)

```
c=u[2..];u(p:xs)=p:u[x|x<-xs,x`mod`p>0];s a b=(sum.filter(>=a).takeWhile(<=b))c

```

`s 1 100 == 1060`

# Answer
> 4 votes
# Perl, 62 chars

```
<>=~/\d+/;map$s+=$_*(1x$_)!~/^1$|(^11+)\1+$/,$&..$';print$s,$/

```

This one uses the prime number regex.

# Answer
> 3 votes
# Ruby 1.9, 63 chars

```
require'prime';p=->a,b{Prime.each(b).select{|x|x>a}.inject(:+)}

```

Use like this

```
p[1,100] #=> 1060

```

Using the `Prime` class feels like cheating, but since the Mathematica solutions used built-in prime functions...

# Answer
> 3 votes
## APL (25 characters)

```
+/((R≥⎕)^~R∊R∘.×R)/R←1↓⍳⎕

```

This is a modification of a well-known idiom (see this page for an explanation) for generating a list of primes in APL.

Example:

```
      +/((R≥⎕)^~R∊R∘.×R)/R←1↓⍳⎕
⎕:
      100
⎕:
      1
1060

```

# Answer
> 3 votes
## Normal Task (Python 3): 95 chars

```
a,b=map(int,input().split())
r=range
print(sum(1%i*all(i%j for j in r(2,i))*i for i in r(a,b+1)))

```

## Bonus Task (Python 3): 119 chars

```
L=iter(map(int,input().split()))
r=range
for a,b in zip(L,L):print(sum(1%i*all(i%j for j in r(2,i))*i for i in r(a,b+1)))

```

# Answer
> 3 votes
# R, 57 characters

```
a=scan();b=a[1]:a[2];sum(b[rowSums(!outer(b,b,`%%`))==2])

```

# Answer
> 3 votes
# Pari/GP (24 characters)

```
s=0;forprime(i=a,b,s+=i)

```

Like some other solutions, this doesn't strictly meet the requirements, as `a` and `b` aren't read from stdin or the command line. I thought it was a nice alternative to the other Pari/GP and Mathematica solutions however.

# Answer
> 3 votes
# Japt, 7 bytes

```
òV fj x

```

Try it here.

# Answer
> 3 votes
# 05AB1E, 5 bytes

```
ŸDp*O

```

Try it online!

```
Ÿ      Push the list [a, ..., b]
 D     Push a duplicate of that list
  p    Replace primes with 1 and everything else with 0
   *   Element-wise multiply the two lists [1*0, 2*1, 3*1, 4*0, ...]
    O  Sum of the final list of primes

```

# Answer
> 3 votes
# C (clang), ~~164~~ ~~138~~ 122 bytes

```
i,x,y,z;main(f){for(scanf("%d %d",&x,&y);x<y;z+=x++*!f)if(f=0,x<2)++x;else for(i=2;x/2/i&&!(f|=x%i++<1););printf("%i",z);}

```

Try it online!

Original code from Programiz. Just modified the code to reduce bytes. Yes, I'm terrible at this.

Code changed thanks to Pedro Maimere, byte count didn't change. Thanks to ceilingcat for golfing 26 bytes, and another 16 bytes.

# Answer
> 3 votes
# Pip, ~~19~~ 17 bytes

```
$+Y1=0N_%,_FIa\,b

```

Attempt This Online!

*-2 thanks to @DLosc*

Uses DLosc's answer to the prime checker challenge

#### Explanation

```
$+Y1=0N_%,_FIa\,b  ; Input on command line
              \,   ; Inclusive range between
             a  b  ; The two inputs
           FI      ; Filtered by
   1=0N_%,_        ; Is prime (see linked answer)
$+                 ; Sum the resulting list

```

Old:

```
$+Y{1=0Na%,a}FIa,Ub  ; Input on command line
                ,    ; Range between
               a     ; The first input
                 Ub  ; To the second input incremented
             FI      ; Filtered by
   {1=0Na%,a}        ; Is prime (see linked answer)
$+Y                  ; Sum the resulting list

```

# Answer
> 3 votes
# Regex  (ECMAScriptRME / Perl / PCRE), 32 bytes

```
^(x*),x*(?=\1)(?!(xx+)\2+$)x\Bx*

```

Takes its input in unary, as two strings of `x` characters whose lengths represent the numbers, joined by a `,` delimiter, specifying an inclusive range. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)

Try it online! / Attempt This Online! \- Perl
Try it online! \- PCRE1
Try it online! / Attempt This Online! \- PCRE2
Try it on replit.com! \- RegexMathEngine, in ECMAScript mode

```
^              # Anchor to start
(x*)           # \1 = lower end of range
,              # Skip over delimiter
x*             # tail += {any number, including zero}
(?=\1)         # Assert that tail ≥ \1
(?!(xx+)\2+$)  # Assert that tail is not composite (i.e., tail is prime or is < 2)
x\Bx*          # if tail ≥ 2, add tail to the number of possible matches; this is
               # equivalent to "(?=xx)x+"

```

# Regex (.NET), 32 bytes

```
x(x*),((?=(xx+)\3+$|(x)+)x\B)*\1

```

Returns its output as the capture count of group `\4`.

Try it online!

```
                   # No need to anchor, as this regex will always match
x(x*)              # \1 = {lower end of range} - 1
                   # This takes advantage of the input specification allowing
                   # us to assume it to be ≥ 1.
,                  # Skip over delimiter; tail = upper end of range
(
    (?=            # Lookahead - is atomic (the first match found is final)
        (xx+)\3+$  # Match if tail is composite (i.e., isn't prime and is ≥ 2)
    |          # or...
        (x)+       # Push {tail} captures onto the Group 4 stack, i.e. add
                   # {tail} to the return value.
    )
    x              # tail -= 1
    \B             # Assert tail > 0
)*                 # Iterate the above as many times as possible (can be zero)
\1                 # Assert tail ≥ \1

```

# Answer
> 2 votes
# Common Lisp, 107 chars

```
(flet((p(i)(loop for j from 2 below i never (= (mod i j) 0))))(loop for x from(read)to(read)when(p x)sum x))

```

only works for starting points \\$\ge 1\\$

# Answer
> 2 votes
## Python 3.1(153 chars):

```
from sys import*
p=[]
for i in range(int(argv[1]),int(argv[2])):
 r=1
 for j in range(2,int(argv[2])):
  if i%j==0and i!=j:r=0
 if r:p+=[i]
print(sum(p))

```

# Answer
> 2 votes
## In Q (95):

```
d:{sum s:{if[2=x;:x];if[1=x;:0];$[0=x mod 2;0;0=min x mod 2+til floor sqrt x;0;x]}each x+til y}

```

Sample Usage:

```
q)d[1;100]
1060

```

# Answer
> 2 votes
# Factor -\> 98

```
:: s ( a b -- n )
:: i ( n -- ? )
n 1 - 2 [a,b] [ n swap mod 0 > ] all? ;
a b [a,b] [ i ] filter sum ;

```

Output:

```
( scratchpad ) 100 1000 s

--- Data stack:
75067

```

# Answer
> 2 votes
# C#, 302 bytes

```
using System;namespace X{class B{static void Main(){long x=long.Parse(Console.ReadLine()),y=long.Parse(Console.ReadLine()),r=0;for(long i=x;i<=y;i++){if(I(i)){r+=i;}}Console.WriteLine(r);}static bool I(long n){bool b=true;if(n==1){b=false;}for(long i=2;i<n;++i){if(n%i==0){b=false;break;}}return b;}}}

```

# Answer
> 2 votes
# R, 85 characters

`x=scan(nmax=2);sum(sapply(x[1]:x[2],function(n)if(n==2||all(n %% 2:(n-1)))n else 0))`

Extremely inefficient! I'm pretty sure it takes O(n^2) time. It might give warnings about coercing a double to a logical.

Deobfuscated:

```
x <- scan(nmax=2)
start <- x[1]
end <- x[2]

#this function returns n if n is prime, otherwise it returns 0.
return.prime <- function(n) {
  # if n is 2, n is prime. Otherwise, if, for each number y between 2 and n, n mod y is 0, then n must be prime
  is.prime <- n==2 || all(n%% 2:(n-1))
  if (is.prime)
    n
  else
    0
}
primes <- sapply(start:end, return.prime)
sum(primes)

```

# Answer
> 2 votes
# Java 8, ~~239~~ ~~237~~ ~~74~~ 73 bytes

```
a->b->{long r=0,t;for(;a<=b;r-=b--==t?~b:0)for(t=1;b%++t%b>0;);return r;}

```

-1 byte thanks to *@ceilingcat*

Try it online.

**Explanation:**

```
a->b->{              // Method with two Long parameters & Long return-type
  long r=0,          //  Result-sum, starting at 0
       t;            //  Temp-long
  for(;a<=b          //  Loop as long as `a` is still smaller than or equal to `b`:
      ;              //    After every iteration:
       r-=           //     Decrease the result-sum by:
          b--==t?    //      If `b` is equal to `t` (which means `b` is a prime):
                     //      (and decrease `b` by 1 afterwards with `b--`)
           ~b        //       Decrease the result-sum by `-b-1`
                     //       (aka Increase the result-sum by `b+1`,
                     //        where `+1` is to account for the earlier `b--`)
          :          //      Else:
           0)        //       Leave `r` the same by decreasing with 0
    for(t=1;         //   (Re)set `t` to 1
        b%++t%b>0;); //   Increase `t` by 1 first with `++t` every iteration,
                     //   and loop as long as `b` is NOT divisible by `t`,
                     //   and `b` is NOT 1 (with the second `%b`)
  return r;}         //  After the nested loop, return the result-sum

```

# Answer
> 2 votes
# Jelly, 3 bytes

```
æRS

```

Try it online!

# Answer
> 2 votes
# Desmos, ~~124~~ 50 bytes

```
f(a,b)=∑_{n=a}^bnsgn((n-1)∏_{k=3}^nmod(n,k-1))

```

Try it on Desmos!

~~I had to waste 23 bytes just for the edge case of 0 and 1(`-\left\{n<2:1,0\right\}`). I feel like this could definitely be golfed further, but I'm not that skilled at Desmos. I especially think that the edge cases 0 and 1 could be handled a lot better than what I'm doing currently.~~

To think I've come so far... just a mere 2.5 years ago I was still a complete noob at Desmos golfing. Now, coming back to this answer 2.5 years later, there are so many golfs that I can spot. Shifting the bounds to remove the curly brackets, better ways to deal with the `n=1` edge case, and some other tiny golfs, resulted in an over 50% reduction in my original code. Truly amazing stuff.

### Explanation

I will explain each sub-expression a little out of order from the actual code, but I feel that this is the best way to understand what the code is doing.

`∑_{n=a}^b`: Summation from `n=a` to `b`. This will iterate through all integers between `a` and `b` inclusive.

`∏_{k=3}^nmod(n,k-1)`: This takes the product of `k=3` to `n` of `mod(n,k-1)`which essentially tests all the possible divisors between `k=2` and `n-1`, and checks if `n` is divisible by `k` with `mod(n,k)` (it is `mod(n,k-1)` in the actual product, which will be explained further below). If `n` is composite then at least one value of `k` will make the `mod` expression equal to `0`, making the entire product equal to `0`. Otherwise, if `n` is a prime, then the product would be a positive integer. The reason why the product goes from `k=3` to `n` instead of the more intuitive `k=2` to `n-1` is because if the upper bound is represented by more than one character, then curly brackets are required to group the characters together. In other words, a product from `k=2` to `n-1` would be `∏_{k=2}^{n-1}`, which is four more bytes than `∏_{k=3}^n`. But because we have shifted the bounds of the product up by one, we will need to subtract one from all instances of `k` in order to compensate for the shift. Hence, we have `k-1` instead of `k` in the `mod` expression. This adds two bytes to our total code length, resulting in a net -2 bytes from doing this bound shifting. Now, because the bounds start from `k=3`, what happens if `n=1` or `2`? When the upper bound is lower than the lower bound, then the product will default to a value of `1`. This is an issue for the `n=1` case, which will result in the product being a positive integer (specifically `1`), but that is undesirable because a positive integer implies that `n=1` is a prime when in reality it isn't a prime. But there is a way to easily fix this...

`(n-1)`: This expression is solely to deal with the `n=1` case. When `n=1`, `n-1` is `0` which causes the entire product to equal `0`. For any other positive value, `n-1` would simply be a positive integer and not affect the overall sign of the product. Note that this fix only works for testing primality for positive integers, but this is okay for our code because the problem specifies that `a` and `b` can be assumed to be at least `1`. To deal with the `n=0` case as well, something like `0^{0^{n-1}}` would probably work.

`nsgn( ... )`: This takes `n` and multiplies it by the sign (`sgn` in the code) of the entire product expression. Remember that if the inside expression is a positive integer, then it is a prime; otherwise, it is composite. By taking the sign of the resulting integer, we will get `1` if `n` is prime and `0` if `n` is composite. Multiplying that by `n` will give `n` and `0` for the respective possibilities.

Now considering that we are taking a summation from `n=a` to `b`, this will essentially add `n` to the total sum if `n` is a prime, but it won't contribute to the sum if `n` is a composite. In other words, it takes the sum of all integers between `n=a` and `b` which are prime. With that, we are done.

# Answer
> 2 votes
# Factor \+ `math.primes math.unicode`, ~~32~~ 23 bytes

```
[ primes-between Σ . ]

```

*-9 bytes* thanks to chunes!

Try it online!

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

```
IœP

```

#### Explanation

```
IœP  # Implicit input
I    # Inclusive range, [a..b]
 œ   # Filtered by:
  P  #  Primality
     # Implicit output of sum (S flag)

```

#### Screenshot

# Answer
> 1 votes
## Perl, 103 chars

```
while(<>){($a,$b)=split/ /;for($a..$b){next if$_==1;for$n(2..$_-1){$_=0if$_%$n==0}$t+=$_;}print"$t\n";}

```

It'll accept multiple space separated lines and give the answer for each :D

# Answer
> 1 votes
**Python 3: 99 chars**

```

l,h=map(int,input().split())
print(sum(p for p in range(l,h+1) if all(p%i for i in range(2,p)))-1)

```

# Answer
> 1 votes
## *Mathematica*, 27

Predefined `a` and `b`:

```
a~Range~b~Select~PrimeQ//Tr

```

As a function (also 27):

```
Tr[Range@##~Select~PrimeQ]&

```

# Answer
> 1 votes
## Python 3: 86 chars

```
a,b=map(int,input().split())
P=k=1
s=0
while k<=b:s+=P%k*k*(k>=a);P*=k*k;k+=1
print(s)

```

Uses the factorial trick with Wilson's Theorem to check whether `k` is prime. `P%k` is `1` if `k` is prime and `0` otherwise. If it is prime, `k` is added to the running sum `s`.

# Answer
> 1 votes
# Python - 194

File fsoe-sum.py:

```
S,E=input()
L={}
n=2
s=0
while n<=E:
        try:
                P=L[n];del L[n]
        except:
                P=[n]
                if S<=n: s+=n
        for p in P:
                m=n+p
                try:
                        if p not in L[m]:L[m].append(p)
                except:
                        L[m] = [p]
        n+=1
print s

```

Filesize is 194 bytes when using tabs to indent and no final newline.

Not the shortest pythonish solution but do you see the enbedded sieve? ;-)

Run:

```
$ python fsoe-sum.py
1,1000000
37550402023
$ python fsoe-sum.py
1,2000000
142913828922
$ python fsoe-sum.py
1000001,2000000
105363426899
$ python -c 'print 142913828922-37550402023'
105363426899

```

# Answer
> 1 votes
# Perl, 94

```
my$s;map{my($a,$b)=($_,0);for(2..$a-1){$a%$_==0&&$b++}$b or$s+=$a}($ARGV[0]..$ARGV[1]);print$s

```

This takes input from the command line. It doesn't use regex.

# Answer
> 1 votes
# GolfScript, ~~27~~ 24 bytes

```
~,>{:x,{)x\%!},,2=},{+}*

```

This is based off of @w0lf's prime number algorithm.

# Answer
> 1 votes
# Haskell, ~~47~~ 44 bytes

```
a!b=sum[x|x<-[a..b],all((<)0.mod x)[2..x-1]]

```

SEJPM helped me save 3 bytes!

# Answer
> 1 votes
## Ruby, 60 bytes

```
require'prime';p=->a,b{eval Prime.each(b).reject{|x|x<a}*?+}

```

## Usage

```
puts p[*gets.split.map(&:to_i)]

```

### Inputs & Outputs

```
2 10     #=> 10
3 10     #=> 8
100 1000 #=> 75067

```

# Answer
> 1 votes
# Casio-Basic, 42 bytes

```
sum(seq(piecewise(isPrime(x),x,0),x,a,b

```

Uses a hybrid/piecewise function that returns the number if it's prime, otherwise return 0. `seq` runs this over the range a to b, then `sum` adds it all up.

39 bytes for the function, 3 bytes to enter `a,b` as parameters.

# Answer
> 1 votes
# Add++, 10 bytes

```
L,d@ßrÞP¦+

```

Try it online!

## How it works

```
D,f,@@,		; Define a dyadic function, f
		; Example arguments:	[2 23]
	d	; Duplicate;	STACK = [2 23 23]
	@	; Reverse;	STACK = [23 23 2]
	ßr	; Range;	STACK = [23 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22]
	Þ	; Filter on:
	  P	;  Primality	STACK = [23 2 3 5 7 11 13 17 19]
	¦+	; Sum;		STACK = [100]
		; Implicitly return top of stack

```

# Answer
> 1 votes
# APL(NARS), 11 chars, 22 bytes

```
{+/⍵/⍨0π¨⍵}

```

test one range:

```
{+/⍵/⍨0π¨⍵}  1..23
  100
{+/⍵/⍨0π¨⍵}  1..22
  77
{+/⍵/⍨0π¨⍵}1..1
  0

```

test two ranges:

```
{+/⍵/⍨0π¨⍵}¨(1..22)(1..23)
  77 100

```

# Answer
> 1 votes
**Python 3: 259 characters** This is a longer solution, but it's more efficient than the one-liner I first posted.

```
import itertools as i
l,h=map(int,input().split())
F=lambda p:lambda x:x%p
def S(s):
 while 1:
  yield (p:=next(s),s:=filter(F(p),s) if p*p<=h else s)[0]
P=lambda:(yield from S(i.count(2)))
print(sum(i.takewhile(lambda e:e<=h,i.dropwhile(lambda e:e<l,P()))))

```

# Answer
> 1 votes
# Whispers v3, 69 bytes

```
> Input
> Input
>> 1…2
>> L’
>> Select∧ 4 3
>> ∑5
>> Output 6

```

Try it online!

simply makes an inclusive range and filters it, then sums it.

# Answer
> 1 votes
# Python 2, 82 bytes

```
for i in range(input(),input()+1):P=n=1;exec'P*=n*n;n+=1;'*~-i;exec P%n*'print;'*i

```

Try it online! Outputs in unary using a newline as a tally mark.

```
for i in range(input(),input()+1):P=n=1;exec'...'*~-i;exec P%n*'...'*i  # trimmed program
for   in                         :     ;             ;                  # for...
    i                                                                   # variable...
for   in                         :     ;             ;                  # in...
         range(       ,         )                                       # [...
               input()                                                  # input...
         range(                 )                                       # , ...,
                       input()                                          # input...
                              +                                         # plus...
                               1                                        # literal...
         range(                 )                                       # ]...
                                     =                                  # set...
                                    n                                   # variable...
                                     =                                  # to...
                                      1                                 # literal
                                   =                                    # set...
                                  P                                     # variable...
                                   =                                    # to...
                                    n                                   # variable
                                        exec                            # execute...
                                            '...'                       # literal...
                                                 *                      # repeated...
                                                  ~                     # negative...
                                                   -                    # negative...
                                                    i                   # variable...
                                                  ~                     # minus 1...
                                                 *                      # times...
                                        exec                            # as Python code
                                                      exec              # execute...
                                                               '...'    # literal...
                                                              *         # repeated...
                                                           P            # variable...
                                                            %           # modulo...
                                                             n          # variable...
                                                              *         # times...
                                                                    *   # repeated...
                                                                     i  # variable...
                                                                    *   # times...
                                                      exec              # as Python code

====================

P*=n*n;n+=1;  # full program
 *=           # set...
P             # variable...
 *=           # to...
P             # variable...
 *=           # multiplied by...
   n          # variable...
    *         # multiplied by...
     n        # variable
        +=    # set...
       n      # variable...
        +=    # to...
          1   # literal...
        +=    # added to...
       n      # variable

====================

print;  # full program
print   # output nothing with a trailing newline

```

# Answer
> 1 votes
# Factor \+ `math.primes`, 37 bytes

```
: f ( x y -- n ) primes-between sum ;

```

Try it online!

# Answer
> 1 votes
# Brachylog, 5 bytes

```
⟦₂ṗˢ+

```

Try it online!

### Explanation

```
⟦₂       Range from the 2 numbers in the Input
  ṗˢ     Select all primes
    +    Sum

```

# Answer
> 1 votes
# Thunno, \\$ 7 \log\_{256}(96) \approx \\$ 5.76 bytes

```
1+:gNkS

```

Attempt This Online!

Takes \\$ b \\$ first, then \\$ a \\$

#### Explanation

```
1+:gNkS  # Implicit input, b then a
1+       # Pop b and push b+1
  :      # Pop both and push [a..b+1)
   gNk   # Filter for primes only
      S  # Sum the resulting list

```

# Answer
> 1 votes
# Stax, 8 bytes

```
Φ└♪Y╓U↨M

```

Run and debug it

This is a packed stax program which unpacks to the following 10 bytes:

```
^|r{|p}f|+

```

Run and debug it

```
^|r{|p}f|+ # takes input a,b
^          # increment b
 |r        # range from a..b+1
   {  }f   # filter by
    |p     # is prime?
        |+ # sum

```

# Answer
> 1 votes
# CJam, 11 bytes

```
),\>{mp},:+

```

Try it online!

Essentially a port of my Stax answer

# Explanation

```
),\>{mp},:+ # function taking a,b
)           # increment b
 ,          # range 0..b+1
  \         # swap to put a on top of stack
   >        # drop a elements from the range 0..b+1, essentially making it range(a,b+1)
    {  },   # filter by
     mp     # primality
         :+ # sum

```

# Answer
> 1 votes
# Arturo, ~~38~~ 36 bytes

```
print∑select..loop arg=>do=>prime?

```

```
print         ; print
∑             ; sum
select        ; select certain items from a block
..            ; range
loop arg=>do  ; eval each command line argument and place on stack
=>prime?      ; are they prime? (select)

```

# Answer
> 1 votes
# Vyxal `s`, 20 bits1, 2.5 bytes

```
ṡ~æ

```

Try it Online!

Somehow, I never noticed the existing answer is actually invalid.

## Explained

```
ṡ~æ
ṡ    # Range [a, b]
 ~æ  # Filtered to only contain primes
# Summed by the s flag

```

# Answer
> 1 votes
# SAS, 163 bytes

I got suggestion that use of macro variables for input is "invalid method", here is other version of the code which basically wraps the original one (look below) inside a `%window` statement (makes it more obfuscated and limits it use to the DMS env. only):

The prompt window for DMS:

```
%window i a 4 b 4;%display i;

```

The code that sums primes and prints result to the log

```
data;array a[&b](. 2:&b);do i=2 to sqrt(&b);if a[i] then do j=2*a[i] by a[i] while(j<=&b);a[j]=.;end;end;x=sum(of a&a--a&b);put x;run;

```

Length of the code which "does the job" effectively stays the same.

Let me share a comment about "invalidity" of the first approach:

Passing input data in all 3 programming interfaces SAS DMS, SAS EG, or SAS Studio can be done:

1. by a SAS dataset,
2. by a text file,
3. hard-coded inside data step, and
4. by macrovariables.

A programmer does not have to wrap-up 4GL code inside a macro to use macrovariables in it, for example the following works perfectly well:

```
%let a=42;

data _null_;
  the_answer=&a.;
  put the_answer;
run;

```

The DMS allows `window` and `display` statements and they macro language counterparts `%window` and `%display` to produce a prompt input window. Unfortunately those are DMS "specific" and not working in the EG or SAS Studio interfaces.

Assuming we are working in the DMS env. For a SAS programmer execution of the following code, which creates and opens prompt input window:

```
%window in
@1 'a:' a 8 'b:' b 8;
%display in;

```

just before the data step and typing in values of a and b

is effectively equivalent to running:

```
%let a=XXX;
%let b=YYY;

```

with `XXX` and `YYY` as values for a and b.

---

* The original post below:\*

input in SAS can be done by macrovariables:

```
%let a=3;
%let b=1000000;

```

the code sums primes and prints result to the log

```
data;array a[&b](. 2:&b);do i=2 to sqrt(&b);if a[i] then do j=2*a[i] by a[i] while(j<=&b);a[j]=.;end;end;x=sum(of a&a--a&b);put x;run;

```

more readable version, `_null_` added to stop dataset creation:

```
%let a=3;
%let b=1000000;
data ;
  array a[&b] (. 2:&b); /* array of integers from 2 to b */
  do i = 2 to sqrt(&b); /* loop until sqrt of b */
    if a[i] then        /* if there is value in the array at i */
      do j=2*a[i] by a[i] while (j<=&b);
        a[j] = .;       /* ... replace all multiplicities of a[i] with missings */
      end;
  end;
  x = sum(of a&a--a&b); /* sum elements for position a to b */
  put x;
run;

```

# Answer
> 1 votes
# SAS, 130 ~~134~~

I got suggestion that use of macro variables for input is "invalid method", here is other version of the code which basically wraps the original one (look below) inside a `%window` statement (makes it more obfuscated and limits it use to the DMS env. only):

The prompt window for DMS:

```
%window i a 4 b 4;%display i;

```

\[Edit: some spaces were not necessary.\] The code that sums primes and prints result to the log

```
data;array a[&b](. 2:&b);do i=2to sqrt(&b);if a[i]then do j=2*a[i]by a[i]while(j<=&b);a[j]=.;end;end;x=sum(of a&a--a&b);put x;run;

```

Length of the code which "does the job" effectively stays the same.

Let me share a comment about "invalidity" of the first approach:

Passing input data in all 3 programming interfaces SAS DMS, SAS EG, or SAS Studio can be done:

1. by a SAS dataset,
2. by a text file,
3. hard-coded inside data step, and
4. by macrovariables.

A programmer does not have to wrap-up 4GL code inside a macro to use macrovariables in it, for example the following works perfectly well:

```
%let a=42;

data _null_;
  the_answer=&a.;
  put the_answer;
run;

```

The DMS allows `window` and `display` statements and they macro language counterparts `%window` and `%display` to produce a prompt input window. Unfortunately those are DMS "specific" and not working in the EG or SAS Studio interfaces.

Assuming we are working in the DMS env. For a SAS programmer execution of the following code, which creates and opens prompt input window:

```
%window in
@1 'a:' a 8 'b:' b 8;
%display in;

```

just before the data step and typing in values of a and b

is effectively equivalent to running:

```
%let a=XXX;
%let b=YYY;

```

with `XXX` and `YYY` as values for a and b.

---

*The original post below:*

input in SAS can be done by macrovariables:

```
%let a=3;
%let b=1000000;

```

the code sums primes and prints result to the log

```
data;array a[&b](. 2:&b);do i=2 to sqrt(&b);if a[i] then do j=2*a[i] by a[i] while(j<=&b);a[j]=.;end;end;x=sum(of a&a--a&b);put x;run;

```

more readable version, `_null_` added to stop dataset creation:

```
%let a=3;
%let b=1000000;
data ;
  array a[&b] (. 2:&b); /* array of integers from 2 to b */
  do i = 2 to sqrt(&b); /* loop until sqrt of b */
    if a[i] then        /* if there is value in the array at i */
      do j=2*a[i] by a[i] while (j<=&b);
        a[j] = .;       /* ... replace all multiplicities of a[i] with missings */
      end;
  end;
  x = sum(of a&a--a&b); /* sum elements for position a to b */
  put x;
run;

```

# Answer
> 0 votes
# Scala, 260 bytes

```
object P extends App{
def c(M:Int)={val p=(false::false::true::List.range(3,M+1).map(_%2!=0)).toArray
for(i<-(3 to M)
if p(i))
{var j=i*i
while(j<M){p(j)=false
j+=i}}
p}
val l=args.map(_.toInt)
val p=c(l(1))
println((l(0)to l(1)).filter(p).map(_.toLong).sum)}

```

A self-written primes-sieve.

```
time scala P 3900000 4000000
25811704341

real    0m8.288s
user    0m6.968s
sys 0m0.456s

```

# Answer
> 0 votes
## Python, 133

A little bit of sorcery:

```
x,y=map(int,raw_input().split())
y+=1
a=range(y)
print sum(i for i in[[i for a[::i]in[([0]*y)[::i]]][0]for i in a[2:]if a[i]]if i>=x)

```

# Answer
> 0 votes
# PowerShell, 94 bytes

```
$a,$b=$args[0,1]
(.{$p=2..$b
while($p){$p[0];$p=@($p|?{$_%$p[0]})}}|
?{$_-gt$a}|
measure -s).sum

```

# Answer
> 0 votes
# F# (141)

One third of the code is for parsing the input.

```
let[|a;b|]=System.Console.ReadLine().Split(' ')
{int a..int b}|>Seq.filter(fun n->n>1&&Seq.forall((%)n>>(<>)0){2..n-1})|>Seq.sum|>printfn"%A"

```

# Answer
> 0 votes
# Perl, 62 with bonus

```
use ntheory":all";while(<>){say vecsum(@{primes(split/\s+/)})}

```

Takes lines with two whitespace separated numbers and prints the sum of primes within the range. Exits when it sees EOF.

47 for the simple case we assume the input magically arrives in $a and $b like a few other solutions:

```
use ntheory":all";forprimes{$s+=$_}$a,$b;say$s

```

or

```
use ntheory":all";say vecsum(@{primes($a,$b)})

```

With a newer module version that can be 39 characters:

```
use ntheory":all";say sum_primes($a,$b)

```

# Answer
> 0 votes
# Julia, 69 bytes

```
a,b=int(split(readline()));println(sum(setdiff(primes(b),primes(a))))

```

This reads a space-delimited pair of integers from STDIN and prints the result to STDOUT. The only thing I've really golfed here is whitespace; otherwise this is probably how I would go about it in a non-golfing context.

Ungolfed + explanation:

```
# Read a line from STDIN, split it into an array on the space, convert
# the elements to integers, and assign the first element to a and the
# second to b
a, b = int(split(readline()))

# Get the primes between a and b inclusive. primes(x) returns the primes
# <= x, so the set difference of primes(b) and primes(a) will get us only
# those between a and b
d = setdiff(primes(b), primes(a))

# Print the sum to STDOUT
println(sum(d))

```

Just realized how old this challenge is.

# Answer
> 0 votes
# Racket, 103 bytes

```
(define(s a b)(for/sum([n(range a(+ b 1))]#:when(and(> n 1)(=(modulo(apply *(range 1 n))n)(- n 1))))n))

```

Try it online!

---

## Explanation

This function receives two range inputs: \\$ 1 \le a \le b \text{ (inclusive)} \\$. It returns the sum of all prime numbers between the range. To determine whether `n` is a prime number or not, two conditions must be satisfied:

The first condition is \\$ n \> 1 \\$ as 1 is not a prime. The second condition is the observation that Wilson's Theorem returns \\$ n - 1 \\$ when \\$n\\$ is a prime.

$$ n - 1 = (n - 1)!\mod n $$

| n | \\$(n - 1)! \mod n \\$ | Is a prime? |
| --- | --- | --- |
| 2 | 1 | Yes |
| 3 | 2 | Yes |
| 4 | 2 | No |
| 5 | 4 | Yes |
| 6 | 0 | No |

The reason for the first condition is that the theorem states that 1 is a prime, but it isn't. The theorem is only accurate when \\$ n \ge 2 \\$.

Putting this into the code is simple:

```
(define (sum-of-primes a b)
  (for/sum ([n (range a (+ b 1))]
            #:when (and (> n 1)
                        (= (modulo (apply * (range 1 n)) n)
                           (- n 1))))
    n))  ; will be collected

```

The `for/sum` loop collects all the values when `#;when` is true. So if the number is a prime number, `for/sum` will add it. Once the loop has finished iterating, it will return the summed up result.

Have a wonderful weekend!

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


title: Reorganize By Arrows

text:
# Question
Title: Reorganize By Arrows
Lets say I was writing something, and I accidentally wrote it in the wrong box:

```
+-------+--------+
| Verbs | Nouns  |
+-------+--------+
| Truck |        |
| eat   | Banana |
|       | Car    |
+-------+--------+

```

So I, being lazy, merely draw an arrow to the space it should be:

```
+-------+--------+
| Verbs | Nouns  |
+-------+--------+
|[Truck]--->     |
| eat   | Banana |
|       | Car    |
+-------+--------+

```

Your job is to make it look pretty - turn it into this:

```
+-------+--------+
| Verbs | Nouns  |
+-------+--------+
|       | Truck  |
| eat   | Banana |
|       | Car    |
+-------+--------+

```

## Rules

* Phrases or words are surrounded by brackets (\[...\])
* ~~Multiline entries are denoted as \[...\]~~ (multiline removed), newline, \[...\]--...--\>. So the arrow always comes out of the **~~bottom~~ right bracket**

For example:

```
+-----------+----------+
|   Verbs   |  Nouns   |
+-----------+----------+
|           |          |
|[is a noun]->         |
| eat       | Banana   |
|           | Car      |
+-----------+----------+

```

Turns into:

```
+-----------+----------+
|   Verbs   |  Nouns   |
+-----------+----------+
|           |          |
|           | is a noun|
| eat       | Banana   |
|           | Car      |
+-----------+----------+

```
* Boxes are bounded by pluses ("+"), and it should be assumed that arrows will not pass over a plus
* There will always be room at the end of an arrow for the word or phrase to fit
* Order matters - the word must appear where the arrow points to, though vertical alignment is not important
* Arrows can turn by 90 degrees at a time, but only between "/" and "\\" (see below)

For example:

```
    +-----------+----------+
    |   Verbs   |  Nouns   |
    +-----------+----------+
    | [Truck]--\|          |
  /------------/|        <--\
  | | eat       | Banana   ||
  | |  /--\     | Car      ||
  | +--|--|-----+----------+|
  \----/  \-----------------/

```

## The Competition

Any input is acceptable (text file, STDIN, etc.)
any readable output is acceptable (text file, STDOUT, etc)

Here are some more examples:

This is code golf, so shortest code wins!

Some test cases:

```
   +--------+----------+-------------+
   | Colors |  Foods   |  Countries  |
   +--------+----------+-------------+
   | red    | pizza    | Switzerland |
 /-->     /---->       |             |
 | |[kale]/ | hot dogs | Brazil      |
 | |     <----------------------\    |
 | | orange |[yellow]\ | [green]/    |
 | +--------+--------|-+-------------+
 \-------------------/

/------------------------------------------\
|                                          |
|  +------------------+----------+-------+ |
|  | frog             |          |       | |
|  | forge            | dog      | eagle | |
|  | foundation       | diligent | ease  | |
|  |[Brother]--\      | down     | elf   | |
|  |           |      |[egg]--\  |[fort]---/
\---->         |      |       |  |       |
   |           \-\    |       \----->    |
   +-------------|----+----------+       |
   |   Boy       \-->            |       |
   |   Bull                      |       |
   |   Browser                   |       |
   +-----------------------------+-------+

             /--------------------------------------\
             |                     /---------------\|
/------------|---------------------/               ||
|            |               /---------------\     ||
|  +---------|-+-----------+-|------+--------|+    ||
\---->       | |  clarinet | \>     | [drums]/|    ||
   | [viola]\\--->         |        +---------+    ||
   |        \----->        |        |         |/---/|
   +-----------+ [violin]\ |        | [cello]--/    |
   |        <------------/ |        +---------+     |
   |           +-----------+      <----------\|     |
   |           |           |        |  [tuba]/|     |
   |           | [piano]\  |        |         |     |
   |        <-----------/  |        |         |     |
   |           +-----------+--------+         |     |
   |           |                    |[trumpet]------/
   | [flute]----->                  |         |
   |           |     saxaphone      |         |
   +-----------+--------------------+---------+

```

# Answer
> 8 votes
# Python, ~~700~~ ~~681~~ ~~676~~ 667 characters

Not fully golfed yet, but wanted to put up an answer.

```
import os
D=map(list,os.read(0,9999).split('\n'))
Z=Q=[-1,0,1,0,-1]
J=''.join
def T(y,x,d,_):c=D[y][x];D[y][x]=' ';d={'\\':3-d,'/':1-d}.get(c,d)%4;j=(y+Q[d],x+Q[d+1],d,c=='>');return c in'<>'and j or T(*j)
def F(y,x,d):
 if y<Y or x<L:
    if D[y][x]=='+':
     if J(D[y]).find('+',x+1)+1:F(y,x+1,1)
     if any((l[x:]+[''])[0]=='+'for l in D[y+1:]):F(y+1,x,2)
    else:D[y][x]='--||'[d];F(y+Q[d],x+Q[d+1],d)
i=0
for l in D:
 I=l.index
 if'+'in l:
    if Z:P,K,L,Z=i,I('+'),J(l).rfind('+'),0
    Y=i
 while'['in l:
    s,e=map(I,'[]');y,x,_,R=T(i,e+1,1,1);W=l[s+1:e]
    if R:D[y][x:x+e-s-1]=W
    else:D[y][x-e+s+2:x+1]=W
    l[s:e+1]=' '*(e-s+1)
 i+=1
F(P,K+1,1);F(P+1,K,2)
for l in D:print J(l)

```

**Strategy**:

I turn the input into a matrix. Then I scan it line by line, finding `[`s. For every `[`, I find the matching `]`, then I call the trace function `T` with the spot immediately to the right of the `]`. The trace function follows the line, replacing the path with `' '`s as it goes, and returns where the word should go. Then I erase the word in the old location and put the word in the new location.

Finally, I call `F`, which recursively reconstructs the boxes.

**Tests**:

```
reorg_test1... True
Input:
+-------+--------+
| Verbs | Nouns  |
+-------+--------+
|[Truck]--->     |
| eat   | Banana |
|       | Car    |
+-------+--------+

Output:
+-------+--------+
| Verbs | Nouns  |
+-------+--------+
|       |   Truck|
| eat   | Banana |
|       | Car    |
+-------+--------+

reorg_test2... True
Input:
+-----------+----------+
|   Verbs   |  Nouns   |
+-----------+----------+
|           |          |
|[is a noun]->         |
| eat       | Banana   |
|           | Car      |
+-----------+----------+

Output:
+-----------+----------+
|   Verbs   |  Nouns   |
+-----------+----------+
|           |          |
|           | is a noun|
| eat       | Banana   |
|           | Car      |
+-----------+----------+

reorg_test3... True
Input:
    +-----------+----------+
    |   Verbs   |  Nouns   |
    +-----------+----------+
    | [Truck]--\|          |
  /------------/|        <--\
  | | eat       | Banana   ||
  | |  /--\     | Car      ||
  | +--|--|-----+----------+|
  \----/  \-----------------/

Output:
    +-----------+----------+
    |   Verbs   |  Nouns   |
    +-----------+----------+
    |           |          |
    |           |   Truck  |
    | eat       | Banana   |
    |           | Car      |
    +-----------+----------+

reorg_test4... True
Input:
   +--------+----------+-------------+
   | Colors |  Foods   |  Countries  |
   +--------+----------+-------------+
   | red    | pizza    | Switzerland |
 /-->     /---->       |             |
 | |[kale]/ | hot dogs | Brazil      |
 | |     <----------------------\    |
 | | orange |[yellow]\ | [green]/    |
 | +--------+--------|-+-------------+
 \-------------------/

Output:
   +--------+----------+-------------+
   | Colors |  Foods   |  Countries  |
   +--------+----------+-------------+
   | red    | pizza    | Switzerland |
   | yellow |   kale   |             |
   |        | hot dogs | Brazil      |
   |green   |          |             |
   | orange |          |             |
   +--------+----------+-------------+

reorg_test5... True
Input:
/------------------------------------------\
|                                          |
|  +------------------+----------+-------+ |
|  | frog             |          |       | |
|  | forge            | dog      | eagle | |
|  | foundation       | diligent | ease  | |
|  |[Brother]--\      | down     | elf   | |
|  |           |      |[egg]--\  |[fort]---/
\---->         |      |       |  |       |
   |           \-\    |       \----->    |
   +-------------|----+----------+       |
   |   Boy       \-->            |       |
   |   Bull                      |       |
   |   Browser                   |       |
   +-----------------------------+-------+

Output:

   +------------------+----------+-------+
   | frog             |          |       |
   | forge            | dog      | eagle |
   | foundation       | diligent | ease  |
   |                  | down     | elf   |
   |                  |          |       |
   |  fort            |          |       |
   |                  |          |   egg |
   +------------------+----------+       |
   |   Boy           Brother     |       |
   |   Bull                      |       |
   |   Browser                   |       |
   +-----------------------------+-------+

reorg_test6... True
Input:
             /--------------------------------------\
             |                     /---------------\|
/------------|---------------------/               ||
|            |               /---------------\     ||
|  +---------|-+-----------+-|------+--------|+    ||
\---->       | |  clarinet | \>     | [drums]/|    ||
   | [viola]\\--->         |        +---------+    ||
   |        \----->        |        |         |/---/|
   +-----------+ [violin]\ |        | [cello]--/    |
   |        <------------/ |        +---------+     |
   |           +-----------+      <----------\|     |
   |           |           |        |  [tuba]/|     |
   |           | [piano]\  |        |         |     |
   |        <-----------/  |        |         |     |
   |           +-----------+--------+         |     |
   |           |                    |[trumpet]------/
   | [flute]----->                  |         |
   |           |     saxaphone      |         |
   +-----------+--------------------+---------+

Output:

   +-----------+-----------+--------+---------+
   |  cello    |  clarinet |   drums|         |
   |           |  trumpet  |        +---------+
   |           |   viola   |        |         |
   +-----------+           |        |         |
   |  violin   |           |        +---------+
   |           +-----------+  tuba  |         |
   |           |           |        |         |
   |           |           |        |         |
   |   piano   |           |        |         |
   |           +-----------+--------+         |
   |           |                    |         |
   |           |  flute             |         |
   |           |     saxaphone      |         |
   +-----------+--------------------+---------+

```

# Answer
> 1 votes
# Python3, 584 bytes:

```
E=enumerate
U=lambda b,x,y:0<=x<len(b)and 0<=y<len(b[0])
def f(b):
 q=[(x,y,'','',0,1)for x,r in E(b)for y,l in E(r)if'['==l]
 while q:
  x,y,w,l,X,Y=q.pop(0)
  if(u:=b[x][y]).isalpha():w+=u
  if u=='/':X,Y=[-X,-Y][::-1]
  if u=='\\':X,Y=[X,Y][::-1]
  if u in'><':
   for i,a in E([w,w[::-1]][u=='<']):b[x][y+Y*i]=a
   continue
  q+=[(x+X,y+Y,w,u,X,Y)]
  b[x][y]=' '
  if'-'==u and U(b,x+1,y)and U(b,x-1,y)and' 'not in(Q:={b[x-1][y],b[x+1][y]})and{'|','+'}&Q:b[x][y]='|'
  if'|'==u and U(b,x,y-1)and U(b,x,y+1)and' 'not in(Q:={b[x][y+1],b[x][y-1]})and{'-','+'}&Q:b[x][y]='-'
 return b

```

Try it online!

---
Tags: code-golf
---