# Question
Title: Sum of the first n elements of the sequence of 9's complement
Let's consider the following sequence:

$$9,8,7,6,5,4,3,2,1,0,89,88,87,86,85,84,83,82,81,80,79,78,77,76,75,74,73,72,71...$$ This is the sequence of \\$9\\$'s complement of a number: that is, \\$ a(x) = 10^d - 1 - x \\$ where \\$ d \\$ is the number of digits in \\$ x \\$. (A061601 in the OEIS).Your task is to add the first \\$n\\$ elements.

### Input

A number \\$n∈\[0,10000\]\\$.

### Output

The sum of the first \\$n\\$ elements of the sequence.

### Test cases

```
0 -> 0
1 -> 9
10 -> 45
100 -> 4050
1000 -> 408600
10000 -> 40904100

```

Standard rules apply. The shortest code in bytes wins.

# Answer
# , 37 bytes

```
f=function(n)sum(10^nchar(1:n-1)-1:n)

```

Try it online!

**note** I left out the check for 0 as I do not think it is part of the sequence as refered to A061601 in the OEIS reference. Adding the check would result in the exact same answer of Giuseppe, which would surely be preferable including the correct answer including 0.
> 5 votes

# Answer
# Wolfram Language (Mathematica), 42 bytes

```
FromDigits[9-IntegerDigits@--n]~Sum~{n,#}&

```

Try it online!

-2 bytes from att
> 4 votes

# Answer
# Julia 1.0, ~~43~~ ~~38~~ 30 bytes

```
!n=n>0&&10^ndigits(~-n)-n+!~-n

```

Try it online!

-5 dingledooper, -8 MarcMush
> 4 votes

# Answer
# , 39 bytes

```
function(n)sum(10^nchar(1:n-1)-1:n)*!!n

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
FNg°<N-O

```

Try it online or verify all test cases.

**Explanation:**

```
F         # Loop `N` in the range [0, (implicit) input):
 Ng       #  Push the length of `N`
   °      #  Take 10 to the power this length
    <     #  Decrease it by 1
     N-   #  Decrease it by `N`
       O  #  Take the sum of the values on the stack
          # (after which the last sum is output implicitly as result -
          # or the implicit input if it was 0 and we never entered the loop)

```
> 3 votes

# Answer
# Vyxal `r`, 8 bytes

No, I'm not Jo King. I found another use for the `r` flag!!!

> It happens once in a blue moon on average

Okay, yes, I said that

```
ʁƛL↵-‹;∑

```

Try it Online! Flagless 9 bytes

## Explanation

So the `r` flag is basically a reverser, which reverses the order of the arguments. That makes it hard to use for long programs, but for short ones like this, it's useful sometimes.

```
ʁƛL↵-‹;∑
ʁ          create list with range(0, n)
 ƛ         open mapping lambda (with loop item n)
  L↵       push 10 to the length of n
    -      n - the latter (because it's reversed)
     ‹;    decrement by 1 and close lambda
       ∑   sum list

```
> 2 votes

# Answer
# Python 3.8 (pre-release), ~~50~~ 44 bytes

Gave a fun recursive solution a go :)

edit: -6 bytes thanks to solid.py

```
f=lambda n:n and f(m:=n-1)-n+10**len(str(m))

```

Try it online!
> 2 votes

# Answer
# Jelly, 7 bytes

```
’æċ⁵_)S

```

A monadic Link accepting a non-negative integer that yields a non-negative integer.

**Try it online!**

### How?

```
’æċ⁵_)S - Link: non-negative integer, n
     )  - for each i in [1..n] (if n is 0 this will yield []):
’       -   decrement -> i-1
   ⁵    -   10
 æċ     -   ceil i-1 to the nearest (positive integer) power of 10
    _   -   subtract i
      S - sum

```
> 2 votes

# Answer
# PowerShell, 57 49 bytes

-8 bytes thanks to @mazzy!

```
0.."$args"-gt0|%{$s-=$_---("1e"+"$_".length)}
+$s

```

Try it online!
> 2 votes

# Answer
# Zsh, 35 bytes

```
for ((x=$1;x--;s+=1e$#x+~x)):
<<<$s
```

Attempt This Online!
> 2 votes

# Answer
# C (gcc), 79 bytes

```
g(n,t,s){t=--n/10;s=n%10+1;n=t*45+s*(19-s)/2+10*(t?s*g(t+1)+(10-s)*g(t)-90:0);}

```

Try it online!
> 2 votes

# Answer
# Behaviour, ~~36~~ 29 bytes

```
f=&#(a*&10^#(""+a)-1-a;>&a+b)

```

My own recently made esolang, so bear with me.

ungolfed and commented

```
f=&
    #(                  // deal with 0 case, convert nil into 0
      a * &             // generate array for n nine complements
        10^#(""+a)-1-a; // nine complements logic
      >&a+b             // reduce array by adding its items
    )

```

Test with:

```
f:0
f:1
f:10

```
> 2 votes

# Answer
# Nibbles, ~~8.5~~ 6.5 bytes

```
+.,$-^~,`p-$~

```

Attempt This Online!

*-2 bytes thanks to Dominic van Essen*

```
+.,$-^~,`p-$~
+             Sum
 .             for n in
  ,             range from 1 to
   $             input
    -          subtract
     ^~         10 to the power of
       ,         length of
        `p        convert to string
          - ~      subtract 1 from
           $        n
                n

```
> 2 votes

# Answer
# Python 3, 49 bytes

*-1 byte thanks to user `friddo`*

```
lambda n:sum(~i+10**len(str(i))for i in range(n))

```

Try it online!
> 1 votes

# Answer
# Japt `-mx`, 8 bytes

+1 byte to work around a bug in Japt.

```
aÓApUs l

```

Try it
> 1 votes

# Answer
# Dyalog APL, 17 bytes

```
+/⍳-⍨1-⍨10*≢∘⍕¨∘⍳

```

`⎕IO←0`.

Try it online!
> 1 votes

# Answer
# Desmos, 49 bytes

```
f(k)=∑_{n=2}^k(10^{1+floor(log(n-1))}-n)+9-0^k9

```

Would be 44 bytes if we didn't have to deal with 0...

Try It On Desmos!

Try It On Desmos! - Prettified

## 48 bytes, port of @tsh's answer

```
t=10^{log(n+0^n)}10
f(n)=tn-(nn+n)/2-(tt-100)/11

```

Try It On Desmos!
> 1 votes

# Answer
# JavaScript, 47 bytes

```
f=n=>(t=10**`${n}`.length)*n+n*~n/2+~-t*~t/11+9

```

Try it online!

There isn't any non-recursive implementation here. So maybe it is worth to include one. But it is longer than current answers...

If your language trunk divide result to int automatically, `+~-t*~t/11` could be changed into `-t*t/11`.

$$ t = 10^{1+\lfloor\log\_{10}n\rfloor} $$ $$ t\cdot n-\frac{n\cdot (n+1)}2-\frac{t^2-100}{11} $$

with special case where \\$n=0\\$
> 1 votes

# Answer
# MATL, 14 bytes

```
:q"10@Vn^q@-vs

```

Try it online!
> 1 votes

# Answer
# J-uby, 32 bytes

```
:*|:sum+(-[S|:+@|:**&10,:~]|+:+)

```

Attempt This Online!

## Explanation

```
:* | :sum + ( -[ S | :+@ | :** & 10, :~ ] | +:+ )

:* |                                               # 0...input
     :sum + (                                   )  # Sum by
              -[                   ,    ] | +:+    #   Sum of
                 S | :+@ | :** & 10                #   10 to the power of the number of digits
                                     :~            #   and two's complement

```
> 1 votes

# Answer
# Raku, 32 bytes

```
0,|[\+] {{S:g/./9/-$_}($++)}...*

```

Try it online!

This is an expression for the infinite sequence of sums.

* `{ ... } ... *` is a lazy, infinite sequence, where the brackets enclose an expression that generates each sequence element.
* `$++` postincrements an anonymous state variable each time the generating function is called, producing the numbers 0, 1, 2, .... Each time, that number is passed to the anonymous function enclosed in the inner brackets. (That saves us having to declare a variable to hold the counter value.)
* `S:g/./9/` converts every digit in the counter to `9`.
* `- $_` subtracts the counter from the previous value.
* `[\+]` produces the sequence of partial sums from the original sequence.
* `0, |` pastes a zero onto the front of the sequence.
> 1 votes

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

```
eDL10@1-_ES

```

Attempt This Online!

#### Explanation

```
   # Implicit input
e  # Map over range(input):
DL #  Duplicate and push the length
10 #  Push ten
@  #  Push 10 ** length
1- #  Subtract one
_  #  Subtract the loop variable
ES # After the map, sum
   # Implicit output

```
> 1 votes

# Answer
# FunStack alpha, 60 bytes

```
Cons 9 Reverse From0 over flatmap Times 9 Pow 10 #N Sum Take

```

Try it at Replit!

### Explanation

First, we construct the infinite list `[9,8,7,6,5,4,3,2,1,0,89,88,87,...]`:

```
#N

```

Natural numbers starting from 0.

```
Times 9 Pow 10

```

Take 10 to the power of each number, then multiply by 9.

```
Reverse From0 over flatmap

```

Create a function that takes a number, generates the range from 0 to that number (exclusive), and reverses it. Then map that function to each number in the above list and flatten the resulting list of lists.

(What we're doing here is really just function composition, but `over` is fewer bytes than `compose` and does the same thing in this case.)

```
Cons 9

```

Stick a 9 on the front of the list.

Now this value gets appended to the program's argument list (which previously contained the input number, N), and we apply the following functions:

```
Take

```

Take the first N values from the infinite list.

```
Sum

```

Sum them.
> 1 votes

# Answer
# JavaScript, 35 bytes

```
f=n=>n&&f(--n)+10**`${n}`.length+~n

```

Try it online!
> 0 votes

# Answer
# , 24 bytes

```
+/@((10&^@#@":->:)"0@i.)

```

Try it online!
> 0 votes

# Answer
# Python 2, 42 bytes

```
f=lambda n:n and-~~n+10**len(`n-1`)+f(n-1)

```

Try it online!
> 0 votes

# Answer
# Ruby, 39 bytes

```
->n{n.times.sum{|x|10**x.to_s.size+~x}}

```

Try it online!
> 0 votes

# Answer
# C (gcc), ~~62~~ ~~50~~ 49 bytes

```
t;f(n){n=n?t=log10(--n?:1),exp10(t+1)+~n+f(n):0;}

```

Try it online!

*Saved a whopping 12 bytes thanks to att!!!*
*Saved a byte thanks to ceilingcat!!!*
> 0 votes

# Answer
# Charcoal, 12 bytes

```
Ｉ↨¹ＥＮ⁻Ｉ×Ｌι9ι

```

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

```
    Ｎ           Input as a number
   Ｅ            Map over implicit range
          9     Literal string `9`
       ×        Repeated by
         ι      Current value
        Ｌ       Length (of string representation)
      Ｉ         Cast to integer
     ⁻          Subtract
           ι    Current value
 ↨¹             Take the sum
Ｉ               Cast to string
                Implicitly print

```

(`Sum()` won't work for an input of `0`.)
> 0 votes

# Answer
# Burlesque, 19 bytes

```
-.{Jln'9j.*j|-}GZ++

```

Try it online!

```
-.   # Decrement (Burlesque runs 0..N inclusive, need to exclude)
{
 J   # Duplicate
 ln  # Number of digits
 '9  # Character 9
 j   # Reorder stack
 .*  # Repeat 9 n_digits times as string
 j   # Reorder stack
 |-  # String subtract (parse and subtract)
}GZ  # Generate for range
++   # Sum

```
> 0 votes

# Answer
# Pari/GP, 30 bytes

```
n->sum(i=0,n-1,10^#Str(i)-1-i)

```

Try it online!
> 0 votes

# Answer
# Haskell, 40 bytes

```
f n=sum[10^length(show$i-1)-i|i<-[1..n]]

```

Attempt This Online!

### Explanation

Implements the spec directly, using the OP's formula with an off-by-one to save a couple bytes.

```
f n=                                     -- Function f when given number n returns:
       [                     |i<-[1..n]] --  List of values for each i from 1 to n:
                  show$i-1               --   Convert i-1 to a string
           length(        )              --   Get its number of digits
        10^                -i            --   10 to that power, minus i
    sum                                  --  Sum that list

```
> 0 votes

# Answer
# Thunno 2 `Sc`, 6 bytes

```
Lıle⁻_

```

Try it online!

#### Explanation

```
Lıle⁻_  # Implicit input
L       # Push [0..input)
 ı      # Map over:
  le    #  10 ** length
    ⁻_  #  - 1 - x
        # Sum the list
        # Implicit output

```
> 0 votes

---
Tags: code-golf, sequence, integer
---


# Question
Title: How many integers contain a number in a specific range
The program should take input the number, the start of the range and the end of the range, and output how many integers the number appears between the start and end of the range, **inclusive**. Both programs and functions are allowed.

## Example Inputs

For example:

```
//Input example 1
3,1,100
//Input example 2
3
1
100
//Input example 3
3 1 100
//Input example 4
a(3, 1, 100);

```

All the above four input examples are valid and all of them mean that `3` is the number in question, `1` is the beginning of the range and `100` the the end of the range.

And then the program should output how many times `3` appears in the range from `1` to `100` **inclusive**. `3` appears in the integers `3`, `13`, `23`, `30`, `31`, `32`, `33`, ..., `93` at a total of 19 times. So the program should output `19` as the output because that is how many times `3` appears in the range from `1` to `100`.

## Rules

* Both programs and functions are allowed.
* All numbers will be integers, meaning that there will **not** be any `float`s or `double`s.
* Note: the sought number will always be in the range `0≤x≤127`. There will be **no** cases where it will be outside this `0≤x≤127` range.
* As in the first example, with the case as `33`, the number `3` will be counted as appearing only **once**, **not** twice.
* The values of the start and end of the range will be between `-65536` and `65535` inclusive.
* The value of range's start will never exceed or equal to range's end. `start < end`
* Also the range is inclusive. For example if the input was `8 8 10`, the range would be `8≤x≤10` and hence the output will be 1.
* Input can be taken in any of the ways shown in the examples. Input can be taken as a string or as a number, any way you wish.

## Test Cases

```
3 1 100
19

3 3 93
19

12,-200,200
24          //This is because 12 appears in -129, -128, ..., -112, -12, 12, 112, 120, 121, 122, ...

123,1,3
0           //This is because all of 123's digits have to appear in the same order

3 33 34
2           //Because 3 appears in 2 numbers: 33 and 34

a(0,-1,1);
1

$ java NotVerbose 127 -12 27
0

```

# Snack Snippet

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
/* Configuration */

var QUESTION_ID = 98470; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 41805; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
> 8 votes
# 05AB1E, 6 bytes

Input in the form: **upper bound**, **lower bound**, **number**.

```
Ÿvy³åO

```

Explanation:

```
Ÿ       # Inclusive range, [a, ..., b]
 vy     # For each element...
   ³å   # Check if the third input is a substring of the number
     O  # Sum up the results

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 10 votes
# Bash, 20 bytes

the obvious answer

```
seq $2 $3|grep -c $1

```

example

```
$ bash golf 3 1 100
19

```

# Answer
> 6 votes
## Perl, 20 bytes

*Saved 2 bytes by using `grep` as in @ardnew's answer.*

Bytecount includes 18 bytes of code and `-ap` flags.

```
$_=grep/@F/,<>..<>

```

Give the 3 numbers on three separate lines :

```
perl -ape '$_=grep/@F/,<>..<>' <<< "3
1
100"

```

# Answer
> 5 votes
# Python 2, ~~47~~ 43 Bytes

Relatively straightforward, making use of Python 2's `repr` short-form.

```
f=lambda n,a,b:a<b and(`n`in`a`)+f(n,-~a,b)

```

Ouput:

```
f(  3,    1, 100) -> 19
f(  3,    3,  93) -> 19
f( 12, -200, 200) -> 24
f(123,    1,   3) -> 0
f(  3,   33,  34) -> 2
f(  0,   -1,   1) -> 1
f(127,   12,  27) -> 0

```

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

-1 thanks to caird coinheringaahing! (Use `w` and filtering to avoiding `@`.)

```
rAwƇ⁵L

```

**TryItOnline!**

Input: Start, End, ToFind

### How?

```
rAwƇ⁵L - Main link: Start, End, ToFind
r      - range: [Start, ..., End]
 A     - absolute values
    ⁵  - third input: ToFind
   Ƈ   - filter keep those (absolute values, a) for which:
  w    -   first index of sublist (implicit digits of ToFind) in (implicit digits of a)
     L - length

```

The default casting of an integer to an iterable for the sublist existence check casts to a decimal list (not a character list), so negative numbers have a leading negative value (e.g. `-122`-\>`[-1,2,2]` which won't find a sublist of `[1,2]`) so taking the absolute value first seems like the golfiest solution.

# Answer
> 4 votes
## JavaScript (ES6), ~~46~~ 45 bytes

```
f=(n,s,e)=>s<=e&&!!`${s++}`.match(n)+f(n,s,e)

```

(My best nonrecursive version was 61 bytes.) Edit: Saved 1 byte thanks to @edc65.

# Answer
> 4 votes
## PowerShell v2+, ~~64~~ ~~62~~ 56 bytes

```
param($c,$a,$b)$(for(;$a-le$b){1|?{$a++-match$c}}).count

```

*-6 bytes thanks to mazzy*

Input via command-line arguments of the form **number lower\_bound upper\_bound**. A little goofy on the notation, because of the semicolons inside the `for` causing parse errors if it's not surrounded in `$(...)` to create a script block. We basically loop upward through `$a` until we hit `$b`, using `Where-Object` (the `|?{...}`) to pull out those numbers that regex `-match` against `$c`. That's encapsulated in parens, we take the `.count` thereof, and that's left on the pipeline and output is implicit.

---

If, however, we guarantee that the range will be no more than 50,000 elements, we can skip the loop and just use the range operator `..` directly, for **~~45~~ 43 bytes**. Since that's not in the challenge specifications, though, this isn't valid. Bummer.

```
param($c,$a,$b)($a..$b|?{$_-match$c}).count

```

# Answer
> 3 votes
# Vim, ~~46~~, 41 bytes

```
C<C-r>=r<tab><C-r>")<cr><esc>jC0<esc>:g/<C-r>"/norm G<C-v><C-a>
kd{

```

Input is in this format:

```
1, 100
3

```

# Answer
> 2 votes
## Haskell, 65 bytes

```
import Data.List
(s#e)i=sum[1|x<-[s..e],isInfixOf(show i)$show x]

```

The `import` ruins the score. Usage example: `((-200)#200)12` -\> `24`.

# Answer
> 2 votes
# Java 7 85 bytes

```
int x(int a,int b,int c){int t=0;for(;b<=c;)if((b+++"").contains(a+""))t++;return t;}

```

# Answer
> 2 votes
# Swift 3, ~~96~~ 93 bytes

```
import Cocoa
func c(n:Int,s:Int,e:Int){print((s...e).filter{"\($0)".contains("\(n)")}.count)}

```

**Edit 1:**

Saved 3 bytes by using shorthand parameters

# Answer
> 2 votes
# Scala, 50 bytes

```
(c:String)=>(_:Int)to(_:Int)count(""+_ contains c)

```

takes the first input curried; call it like this: `f("12")(-200,200)`

Explantion:

```
(c:String)=>  //define an anonymous function taking a string parameter
  (_:Int)     //create a range from an anonymous int parameter
  to          //to
  (_:Int)     //another anonymous int parameter
  count(      //and count how many...
   ""+_       //elements converted to a string
   contains c //contain c
  )

```

# Answer
> 2 votes
# R, 32 bytes

Quite straightforward:

```
function(a,b,c)sum(grepl(a,b:c))

```

# Answer
> 1 votes
# JavaScript, ~~46~~ 45 bytes

```
f=(i,s,e)=>s>e?0:RegExp(i).test(s)+f(i,++s,e)

```

Recursively count until start \> end

Edit: Switch to RegExp test to save a byte

# Answer
> 1 votes
# PHP, ~~68~~ 63 bytes

```
for($a=$argv;$a[2]<=$a[3];)$o+=strstr($a[2]++,$a[1])>'';echo$o;

```

use like:

```
 php -r "for($a=$argv;$a[2]<=$a[3];)$o+=strstr($a[2]++,$a[1])>'';echo$o;" 3 1 100

```

edit: 5 bytes saved thanks to Titus

# Answer
> 1 votes
# C#, 71 bytes

Beat my Java answer thanks to lambdas

```
(t,l,u)=>{int d=0;for(;l<=u;)if((l+++"").Contains(t+""))d++;return d;};

```

# Answer
> 1 votes
# Ruby 44 bytes

```
m=->(n,s,f){(s..f).count{|x|x.to_s[/#{n}/]}}

```

Test Cases:

```
m.(3,1,100)     #=> 19
m.(3,3,93)      #=> 19
m.(12,-200,200) #=> 24
m.(123,1,3)     #=>  0
m.(3,33,34)     #=>  2
m.(0,-1,1)      #=>  1
m.(127,-12,27)  #=>  0

```

# Answer
> 1 votes
# C, ~~143~~ 135 bytes

Thanks to @Kritixi Lithos for helping save 8 bytes

Surely this can be done better, but its the best I've got for now. C doesn't handle strings very gracefully, so naturally it takes quite a few operations.

```
int C(int N,int l,int h){char b[99],n[99];int t=0,i=1;sprintf(n,"%d",N);for(;i<=h;i++){sprintf(b,"%d",i);if(strstr(b,n))++t;}return t;}

```

**Ungolfed + program**

```
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int C(int N,int l,int h)
{
    char b[99], n[99];
    int t=0,i=1;
    sprintf(n,"%d",N);
    for(;i<=h;i++)
    {
        sprintf(b,"%d",i);
        if(strstr(b,n))
            ++t;
    }
    return t;
}

int main()
{
  printf("%d\n", C(3, 1, 100));
}

```

# Answer
> 1 votes
# PHP, 62 bytes

Pretty straight forward approach:

```
<?=count(preg_grep('/'.($a=$argv)[1].'/',range($a[2],$a[3])));

```

Try it online

# Answer
> 1 votes
# Japt, ~~14~~ 8 bytes

Takes the integer to be found as the last input value.

```
õV èÈsøW

```

Try it online

---

## Explanation

```
             :Implicit input of integers U=start, V=end & W=number
õV           :Range [U,V]
    È        :Map
     s       :  Convert to string
      øW     :  Contains W?
   è         :Count truthy values

```

# Answer
> 1 votes
# Powershell, 48 bytes

According to the rule, the range can contain more than 50,000 elements. So we can't use the range operator `..` directly. Thanks AdmBorkBork.

Straightforward:

```
param($c,$a,$b)for(;$a-le$b){$i+=$a++-match$c}$i

```

Test script:

```
$f = {

param($c,$a,$b)for(;$a-le$b){$i+=$a++-match$c}$i

}

@(
    ,(19, 3,1,100)
    ,(19, 3,3,93)
    ,(24, 12,-200,200)
    ,(0, 123,1,3)
    ,(2, 3,33,34)
    ,(1, 0,-1,1)
    ,(0, 127,-12,27)
    ,(44175, 0,-65536,65535)
) | % {
    $e,$a = $_
    $r = &$f @a
    "$($e-eq$r): $r"
}

```

Output:

```
True: 19
True: 19
True: 24
True: 0
True: 2
True: 1
True: 0
True: 44175

```

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

```
÷ṡƛS?hc

```

Try it Online!

# Answer
> 0 votes
# Java, ~~92~~ ~~89~~ 71 bytes

Now with lambdas!

```
(t,l,u)->{int z=0;for(;l<=u;)if((l+++"").contains(t+""))z++;return z;};

```

Old 89 byte function solution:

```
int d(int t,int l,int u){int a=0,i=l;for(;i<=u;)if((i+++"").contains(t+""))a++;return a;}

```

Hooray for the super increment function!

# Answer
> 0 votes
## GolfSharp, 41 bytes

```
(w,q,e)=>r(q,1+e-q).w(n=>n.T().I(w)).L();

```

### A 45 byte version:

---

```
(w,q,e)=>r(q,1+e-q).w(n=>n.T().I(w.T())).L();

```

# Answer
> 0 votes
# Groovy, 48 bytes

```
{a,b,c->(a..b).collect{"$it".count("$c")}.sum()}

```

# Answer
> 0 votes
## Racket 91 bytes

```
(for/sum((i(range s(+ 1 e))))(if(string-contains?(number->string i)(number->string d))1 0))

```

Ungolfed:

```
(define(f d s e)
  (for/sum ((i (range s (+ 1 e))))
    (if(string-contains?
        (number->string i)
        (number->string d))
       1 0 )))

```

Testing:

```
(f 3 1 100)
(f 3 3 93)
(f 12 -200 200)
(f 123 1 3)
(f 3 33 34)
(f 0 -1 1)

```

Output:

```
19
19
24
0
2
1

```

# Answer
> 0 votes
# Axiom bytes 90

```
f(y,a,b)==(c:=0;for x in a..b repeat(if position(y::String,x::String,1)~=0 then c:=c+1);c)

```

results

```
(3) -> f(3,1,100)=19,f(3,3,93)=19,f(12,-200,200)=24,f(123,1,3)=0,f(3,33,34)=2
   (3)  [19= 19,19= 19,24= 24,0= 0,2= 2]
                                  Type: Tuple Equation NonNegativeInteger
(4) -> f(0,-1,1)=1, f(127,12,27)=0
   (4)  [1= 1,0= 0]
                                  Type: Tuple Equation NonNegativeInteger

```

# Answer
> 0 votes
## Mathematica, 70 bytes

```
(w=ToString;t=0;Table[If[StringContainsQ[w@i,w@#1],t++],{i,#2,#3}];t)&

```

**input**

> \[12,-200,200\]

**output**

> 24

# Answer
> 0 votes
## Clojure, 65 bytes

```
#(count(for[i(range %2(inc %3)):when(some(set(str %))(str i))]i))

```

# Answer
> 0 votes
## PHP, 56 Bytes

run as pipe **Try it online**

**Input**

```
$argv = [number_to_find, range_start, range_end];

```

**Code**

```
<?=substr_count(join(range(($a=$argv)[1],$a[2])),$a[0]);

```

**Explanation**

```
#substrcount, counts the aparitions of a subtring in a string
substr_count(
           join( range(($a=$argv)[1],$a[2])), # String with the range
           $a[0]);                            # The number you are looking for

```

# Answer
> 0 votes
# Perl 6, 32 bytes

```
{+grep *.contains($^a),$^b..$^c}

```

Try it online!

# Answer
> 0 votes
# Vyxal `rs`, 5 bytes

```
_ṡ?vc  # main program

```

```
_      # discard the initial number
 ṡ     # inclusive range over implicit inputs
  ?    # number to be checked
   vc  # vectorized contains, sum the list

```

I had to use -r because v vectorizes the first part of the stack otherwise (?)

Try it Online!

# Answer
> 0 votes
# Thunno 2, 3 bytes

```
IƝc

```

Try it online!

#### Explanation

```
IƝc  # Implicit input
I    # Inclusive range between the first two inputs
 Ɲ   # Join it on newlines
  c  # Count occurrences of the third input
     # Implicit output

```

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


title: Inverse Deltas of an Array

text:
# Question
Title: Inverse Deltas of an Array
Your task is to, given an array of signed 32 bit integers, recompile it with its inverse deltas. For example, the list

```
1  3  4  2  8

```

holds the deltas:

```
  2  1 -2  6

```

which are then negated, yielding:

```
 -2 -1  2 -6

```

and recompiled, yielding:

```
1 -1 -2  0 -6

```

as the final result.

## Input/Output

You will be given a list/array/table/tuple/stack/etc. of signed integers as input through any standard input method.

You must output the modified data once again in any acceptable form, following the above delta inversion method.

You will receive N inputs where `0 < N < 10` where each number falls within the range `-1000 < X < 1000`

## Test Cases

```
5 6 7 8          -> 5 4 3 2
1 3 4 2 8        -> 1 -1 -2 0 -6
32 18 25 192 199 -> 32 46 39 -128 -135

```

## Notes

* You are not restricted to the delta based method: if you can work out the easier method *(which shouldn't be too hard)*, you're free to use it.
* As stated in above, you will always receive at least 1 input, and no more than 9.
* The first number of the output must **always** be the first number of the input, if this is not the case, your method is incorrect.
* Only Standard Input Output is accepted
* Standard loopholes apply
* This is , so the lowest byte-count wins!
* Have fun!

## We have a winner.

Dennis's Jelly Answer at a Tiny 3 Bytes has taken home the gold, due to the fact that I am under the impression it cannot be beaten.

I was mildly disappointed I didn't get to see an answer based on the original spec, however, I may later put a bounty on precisely that.

# Answer
# Jelly, ~~7~~ 3 bytes

```
ḤḢ_

```

Try it online!

### Background

The deltas of **(a, b, c, d)** are **b - a**, **c - b**, and **d - c**. Cumulatively reducing **(a, b - a, c - b, d - c)** by subtraction yields **a - (b - a) = 2a - b**, **2a - b - (c - b) = 2a - c**, and **2a - c - (d - c) = 2a - d**, so the correct result is **(2a - a, 2a - b, 2a - c, 2a - d)**.

### How it works

```
ḤḢ_  Main link. Argument: A (array)

Ḥ    Unhalve; multiply all integers in A by 2.
 Ḣ   Head; extract first element of 2A.
  _  Subtract the elements of A from the result.

```
> 31 votes

# Answer
# Python 2, 30 bytes

```
lambda x:[x[0]*2-n for n in x]

```

Test it on Ideone.

### How it works

The deltas of **(a, b, c, d)** are **b - a**, **c - b**, and **d - c**. Cumulatively reducing **(a, b - a, c - b, d - c)** by subtractiong yields **a - (b - a) = 2a - b**, **2a - b - (c - b) = 2a - c**, and **2a - c - (d - c) = 2a - d**, so the correct result is **(2a - a, 2a - b, 2a - c, 2a - d)**.
> 12 votes

# Answer
# Mathematica, 8 bytes

```
2#-{##}&

```

Unnamed function taking an indeterminate number of arguments. This uses an "easy" way: negates the entire list and adds twice the (original) first element.

Called for example like `2#-{##}&[1,3,4,2,8]`; returns a list like `{1,-1,-2,0,-6}`.
> 8 votes

# Answer
# JavaScript (ES6), 21

Thx @Dennis

```
l=>l.map(v=>l[0]*2-v)

```
> 6 votes

# Answer
# 05AB1E, 4 bytes

```
¬·s-

```

Try it online! or as a Test suite

**Explanation**

```
¬     # head of input list
 ·    # multiplied by 2
  s   # swap with input list
   -  # subtract

```
> 4 votes

# Answer
# Perl 6,  ~~40~~  16 bytes

```
{[\+] .[0],|.rotor(2=>-1).map({[-] @_})}

```

```
{.map(.[0]*2-*)}

```

## Expanded:

```
{ # bare block lambda with single implicit parameter ｢$_｣ ( input is a List )

  [\[+]]  # triangle reduce the following using ｢&infix:<+>｣

    .[0], # the first value

    |(    # Slip this list into outer one ( Perl 6 doesn't auto flatten )

      .rotor( 2 => -1 ) # take the input 2 at a time, backing up 1
      .map({ [-] @_ })  # reduce the pairs using ｢&infix:<->｣

    )
}

```

```
{ # bare block lambda with single implicit parameter ｢$_｣ ( input is a List )

  .map(          # map over the inputs
    .[0] * 2 - * # take the first value multiply by 2 and subtract the current value
    #          ^- this makes the statement a WhateverCode, and is the input
  )
}

```
> 4 votes

# Answer
# ARM (Thumb), 16 bytes

```
.section .text
.global func
.thumb
// void func(int* arr, int len)
// arr[i] = 2*arr[0] - arr[i] for each i
// r0 = arr, r1 = len, r2 = arr[0], r3 = arr[i]
func:
    ldr r2, [r0, #0]         // 6802        int head = *arr;
.loop:                       //             do {
    ldr r3, [r0, #0]         // 6803        int cur = *arr;
    rsb r3, r3, r2, lsl #1   // ebc3 0342   cur = (head << 1) - cur;
    stmia r0!, {r3}          // c008        *arr++ = cur;
    sub r1, #1               // 3901        len -= 1;
    bne .loop                // d1f9        } while (len != 0);
    bx lr                    // 4770        return;

```

Uses the formula, which nicely fits into exactly four registers in use. The `stm` tip was used to overwrite the value and advance the pointer in a single narrow instruction, and a wide `rsb` instruction was used to evaluate exactly what we want. (I know it's possible to do with a 3-operand `sub` and then an `add` for the same byte count, but I figured a single instruction would add some coolness.)
> 3 votes

# Answer
# Python, 44 bytes

```
lambda l:[l[0]]+[x-(x-l[0])*2for x in l[1:]]

```

This uses the "Easier method".
> 2 votes

# Answer
# Pyth, 5 bytes

```
-LyhQ

```

Online Interpreter!
> 2 votes

# Answer
# R, ~~23~~ ~~18~~ 17 bytes

```
x=scan();2*x[1]-x

```

auto-vectorisation and default print to the rescue!
> 2 votes

# Answer
# Haskell, 20 19 bytes

```
f(x:r)=x:map(2*x-)r

```

Same solution as Dennis, thank you for your idea of `2a - x`.

Saved one byte thanks to Christian Severs.
> 2 votes

# Answer
# Ruby, 23 bytes

```
->l{l.map{|x|l[0]*2-x}}

```

Not particularly original.
> 2 votes

# Answer
# Brain-Flak, 76 Bytes

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

```

Try it Online!

**Explanation:**

```
Part 1:
(      )                                        # Push:
 []                                             # the height of the stack
   [()]                                         # minus 1
        {                                  }    # While the height - 1 != 0:
         {}                                     # Pop the height
           (({})<                               # Hold onto the top value, but put it back.
                                                # This ensures that the top value is always
                                                # what was the first element of input
                 (            )                 # Push:
                  ({}){}                        # Top * 2
                        [{}]                    # minus the next element
                            <> <>               # onto the other stack

                                 >)             # Put back the element we held onto.
                                   (      )     # Push:
                                    []          # The height of the stack
                                      [()]      # Minus 1
                                            {}  # Pop the counter used for the height
Part 2:
({}<                                            # Hold onto the top element.
                                                # This was the first number for input
                                                # so it needs to end up on top
    <>                                          # Switch stacks
      ([])                                      # Push the height of the stack
          {              }                      # While the height != 0:
           {}                                   # Pop the height
             (    )                             # Push:
              {}                                # The top element of this stack
                <>                              # onto the other stack
                   <>                           # and switch back
                     ([])                       # Push the new height of the stack
                          <>                    # After every element has switched stacks
                                                # (which reverses their order),
                                                # switch stacks
                            >)                  # Push the first element back on

```
> 2 votes

# Answer
# Labyrinth, 34 bytes

```
?:_2*}
@    _
)\?_1"
,    ;
!`-}:{

```

Try it online!

Uses @Dennis's `(2a - a, 2a - b, 2a - c, 2a - d)` approach.

The yellow tiles are for control flow. In this 2D programming language, the program starts at the top-left-most tile moving east to start. At junctions, the direction is determined by the sign of the top of the main stack. Blank tiles are walls.

## Green

This section saves 2a to the auxilary stack.

* `?` Get the first number and push it to the top of the main stack
* `:` Duplicate the top of the stack
* `_2` Push two to the top of the stack
* `*` Pop `y`, pop `x`, push `x*y`
* `}` Move the top of the main stack to the top of the auxilary stack.
* `_` Push zero to the top of the stack

## Orange

This section subtracts 2a from the current number, negates the result, outputs the result, gets the next character (the delimeter), exits if EOF, outputs a newline, gets the next number.

* `"` Noop. If coming from the north, the top of the stack will be zero and the program will continue south. If coming from the west, the top of the stack will be one and the program will turn right (continuing south)
* `;` Discard the top of the stack. As the zero or one is only used for control flow, we need to discard these
* `{` Move the top of the auxilary stack (2a) to the top of the main stack
* `:` Duplicate the top of the main stack
* `}` Move the top of the main stack to the top of the auxilary stack
* `-` Pop `y`, pop `x`, push `x-y`
* `\`` Negate the top of the stack. This and the previous three operations have the effect of`-(x-2a) = 2a-x\`
* `!` Pop the top of the stack and output it as a number
* `,` Push the next character (which will be the delimiter) or negative one if EOF
* `)` Increment the top of the stack. If the last character is EOF, then the top of the stack will now be zero and the program will continue straight to the `@` and exit. If the last character was a delimeter, then the top of the stack will be positive causing the program to turn right and continue east to the `\`
* `\` Output a newline
* `?` Get the next number
* `_1` Push one to the top of the stack in order to turn right at the junction
> 2 votes

# Answer
# Vyxal, 3 bytes

```
dh-

```

Try it Online!

Dennis port

```

d   # Double the array
 h  # Take the first
  - # Subtract

```

Or, by implementing the original spec,

# Vyxal 2.5, 5 bytes

```
¯?hp¦

```

Try it Online!

```
¯     # Deltas (negated, this is a bug, and will be fixed, that is why it's 2.5)
 ?hp  # Prepend the first item of input
    ¦ # Take the cumulative sum

```
> 2 votes

# Answer
## Pyke, ~~5~~ 4 bytes

```
h}m-

```

Try it here!
> 1 votes

# Answer
# PHP, 48 bytes

```
for(;''<$c=$argv[++$i];)echo-$c+2*$a=$a??$c,' ';

```

Using the technique from Dennis. Use like:

```
php -r "for(;''<$c=$argv[++$i];)echo-$c+2*$a=$a??$c,' ';" 1 3 4 2 8

```

Non-Dennis 55 byte version:

```
for(;''<$c=$argv[++$i];$l=$c)echo$a+=($l??$c*2)-$c,' ';

```
> 1 votes

# Answer
# APL, 8 bytes

```
+\⊃,2-/+

```

Explanation:

```
+\           ⍝ running sum of
  ⊃          ⍝ first item of list
   ,         ⍝ followed by
    2-/      ⍝ differences between every pair in
       +     ⍝ input list

```

Test cases:

```
      ( +\⊃,2-/+ ) ¨ (5 6 7 8) (1 3 4 2 8) (32 18 25 192 199)
┌───────┬────────────┬──────────────────┐
│5 4 3 2│1 ¯1 ¯2 0 ¯6│32 46 39 ¯128 ¯135│
└───────┴────────────┴──────────────────┘

```
> 1 votes

# Answer
## Labyrinth, 24 bytes

```
+:}:?
}
<}}?;%):,\!-{:{>

```

Input and output format are linefeed-separate lists (although the input format is actually a lot more flexible). The program terminates with an error.

Try it online!

I've got two other solutions at this byte count, which work basically the same but use somewhat different control flow.

```
:+:}:?
{
,}-!
?  {
:";\@

```

```
{:+:}:?
_
<>__-?:;%):,\!

```

### Explanation

The instruction pointer (IP) starts moving east along the first line, but all the commands before the `?` are basically no-ops on the global state, since we're not using stack depth commands anywhere. So the code really starts at the `?` going west, since the IP turns around when it hits the dead end.

The code therefore starts with the following linear bit of code:

```
?:}:+}

```

This simply sets us up with a copy of `2a` to use the `[2a - a, 2a - b, 2a - c, ...]` formula.

```
?   Read first integer a.
:}  Move a copy off to the auxiliary stack.
:+  Multiply a by 2 (by adding it to itself).
}   Move that off to the auxiliary stack as well.

```

We now enter the main loop of the program, using a fairly standard trick to loop through a single line of code:

```
<...>

```

Note that the stack will be empty whenever we hit the `<` so we know we'll get zeros there. The `<` then rotates the entire line left, taking the IP with it, so we get this:

```
...><

```

The IP then has to move left, where the `>` shifts the line back into its original place (to prepare it for the next iteration). Then the line is simply executed from right to left, so a single loop iteration is this:

```
{:{-!\,:)%;?}}

```

The catch when working with a loop of this type is that you can't work with any form of conditional execution, since Labyrinth doesn't have a way to skip code. Therefore, we will terminate the program with a division by zero when we hit EOF. Here is a breakdown of each loop iteration.

```
{:   Pull 2a back to the main stack and make a copy.
{    Pull the latest value i of the input list back to main as well.
-    Compute 2a-i/
!\   Print it with a trailing linefeed.
,    Read a character. If there are input elements left, this will be some
     form of separator character, and therefore a positive value x. However,
     at the end of the program, this will give -1.
:)   Make an incremented copy.
%    Try to to compute x%(x+1). This will error out at EOF.
;    Discard the result of the division.
?    Read the next input value.
}}   Move that and the remaining copy of 2a back to the auxiliary stack.

```
> 1 votes

# Answer
# Factor, 26 bytes

```
[ dup first 2 * v-n vneg ]

```

Try it online!
> 1 votes

# Answer
# , 7 bytes

```
-~+:@{.

```

Try it online!
> 1 votes

# Answer
# C++14, 36 bytes

As unnamed lambda modifying its input:

```
[](auto&c){for(auto&x:c)x=2*c[0]-x;}

```

Using the technique from Dennis. Works for any container like `int[]` or `vector<int>`.

Usage:

```
#include<iostream>

auto f=
[](auto&c){for(auto&x:c)x=2*c[0]-x;}
;

int main(){
  int a[] = {1,  3,  4,  2,  8};
  f(a);
  for(auto&x:a)
    std::cout << x << ", ";
  std::cout<<"\n";
}

```
> 0 votes

# Answer
# CJam, 16 bytes

Input format: `[1 2 3 4]`. Uses the easy formula.

```
l~_(2*/;a/,@@*.-

```

**Explanation:**

```
l~_(2*/;a/,@@*.-
l~_                     e#Read input twice into an array. Stack: [1 2 3 4] [1 2 3 4]
   (                    e#Get first element of the array. Stack: [1 2 3 4] [2 3 4] 1
    2*                  e#Multiply by two. Stack: [1 2 3 4] [2 3 4] 2
      /;                e#Discard second element. Stack: [1 2 3 4] 2
        a               e#Wrap into an array. Stack: [1 2 3 4] [2]
         /,             e#Rotate and get length. Stack: [2] [1 2 3 4] 4
           @@           e#Rotate twice. Stack: [1 2 3 4] 4 [2]
            *           e#Repeat len times. Stack: [1 2 3 4] [2 2 2 2]
             .-         e#Vectorized substraction. Stack: [-1 0 1 2]
                        e#Implictly print

```

Sorry for no test link. I guess SE don't like it's links with brackets inside.
> 0 votes

# Answer
# Pushy, 9 bytes

```
{&}2*K~-_

```

Give arguments as comma-seperated values on cmd line: `$ pushy invdeltas.pshy 1,3,4,2,8`. Here's the breakdown, with example stack:

```
           % Implicit: Input on stack              [1, 3, 4, 2, 8]
{&}        % Copy first item, put at end of stack  [1, 3, 4, 2, 8, 1]
   2*      % Multiply by 2                         [1, 3, 4, 2, 8, 2]
     K~    % Negate everything on stack            [-1, -3, -4, -2, -8, -2]
       -   % Subtract last item from all           [1, -1, -2, 0, -6]
        _  % Print whole stack

```

Note: this can be 8 bytes if backwards output is allowed: `@&2*K~-_`
> 0 votes

# Answer
# Perl, 26 + 3 (`-pla` flag) = 29 bytes

```
$_="@{[map$F[0]*2-$_,@F]}"

```

or

```
$_=join$",map$F[0]*2-$_,@F

```

Using:

```
perl -plae '$_="@{[map$F[0]*2-$_,@F]}"' <<< "32 18 25 192 199"

```
> 0 votes

# Answer
# Dyalog APL, 5 bytes

`-+2×⊃`

this is a 5-train, it parses like two nested 3-trains ("forks"): `-+(2×⊃)`

reads like: the negation (`-`) of the whole array plus (`+`) twice () the first element ()
> 0 votes

# Answer
# ised, 11 bytes

```
2*$1_0-$1

```

Invocation: `ised --l 'file with input.txt' '2*$1_0-$1`

(edit: corrected by stealing the algebra from Dennis)
> 0 votes

# Answer
# Wonder, 17 bytes

```
@->#@- *2:0#1#0#0

```

Not sure why I didn't post this earlier. Usage:

```
(@->#@- *2:0#1#0#0)[5 6 7 8]

```

More readable:

```
@(map @
  - (
    * 2 get 0 #1
  ) #0
) #0

```
> 0 votes

# Answer
# Zsh, 18 bytes

```
for a;<<<$[$1*2-a]

```

Try it online!
> 0 votes

# Answer
# Japt `-m`, 4 bytes

```
nWÎÑ

```

Try it here
> 0 votes

# Answer
# Halfwit, 3.5 bytes

```
+><iN+

```

Try It Online!

Dennis port.

```
+      # Double the input, adding it to itself
 ><i   # Get the first one
    N+ # Subtract from the input

```

Once again, I'm reminded of how annoying Halfwit's minimalism is to program with.
> 0 votes

# Answer
# Desmos, 12 bytes

```
f(l)=2l[1]-l

```

Try It On Desmos!
> 0 votes

# Answer
# Thunno 2, 3 bytes

```
Ḍh_

```

Try it online!

Port of Dennis's Jelly answer.

#### Explanation

```
Ḍh_  # Implicit input
Ḍ    # Double each number
 h   # Take the first item
  _  # Subtract input from this
     # Implicit output

```
> 0 votes

---
Tags: code-golf, integer
---


title: Goldbach's conjecture

text:
# Question
Title: Goldbach's conjecture
Write a program that prompts the user for an even integer greater than 2.

Given Goldbach’s conjecture that every even integer greater than 2 can be expressed as the sum of two primes, print out two prime numbers which, when added together, provide the requested even number. Edit: the program only has to print A PAIR of primes, not all. For example:

4 : 2 + 2

6: 3 + 3

8: 3 + 5

10: 5 + 5 or 3 + 7

# Answer
# APL, 34 or 44 bytes

The first version is **34** symbol long and is restricted to characters from the original single-byte APL charsets, such as the one still supported in Dyalog APL:

```
↑c/⍨n=+/¨c←,∘.,⍨v/⍨~v∊v∘.×v←1↓⍳n←⎕

```

Explanation:

```
                               n←⎕   ⍝ ask for a number, store as n
                          v←1↓⍳n     ⍝ generate all integers from 2 to n
                      v∘.×v          ⍝ compute the product table of any two such integers
                v/⍨~v∊               ⍝ select those that don't appear in the product table
         c←,∘.,⍨                     ⍝ generate all possible pairs of these primes
    n=+/¨c                           ⍝ check which pairs have a sum equal to n
↑c/⍨                                 ⍝ take the first that does

```

---

The second version is only **22** symbol long, because it exploits the `π` function to check for prime numbers, but that's only available in NARS2000 which uses Unicode, so the byte count is **44** in UCS-2:

```
2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1

```

Explanation:

```
                   ⎕    ⍝ ask for a number N
                  ⍳ -1  ⍝ generate all naturals from 1 to N-1
             (⍪,⌽)      ⍝ arrange it into a table of all pairs of naturals with sum N
     {∧/0π⍵}            ⍝ check which pairs are made of all primes
2⍴(⌿⍨       )           ⍝ return the first pair that does

```

**Examples**

(⎕: is the prompt asking for a number)

```
      2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
      4
2 2
      2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
      6
3 3
      2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
      8
3 5
      2⍴(⌿⍨{∧/0π⍵})(⍪,⌽)⍳⎕-1
⎕:
      124
11 113

```
> 11 votes

# Answer
# Python 2, ~~75~~ 71 bytes

```
n=input();k=m=1;p={0}
while{n-k,k}-p:m*=k*k;k+=1;p|={m%k*k}
print n-k,k

```

Test it on Ideone.

### How it works

We use a corollary of Wilson's theorem:

At all times, the variable **m** is equal to the square of the factorial of **k - 1**; **k** starts at value **1** and **m** at value **0!² = 1**. The set **p** will consist of **0** and all prime numbers up to the current value of **k**.

In each iteration, we first check if both **n - k** and **k** belong to **p**, which is true if and only if the set difference of **{n-k, k}** and **p** is empty. If it is, the condition is falsy and the loop continues.

Note that **k \> 0**, and **{n - k, k}** will satisfy the condition for some positive value of **n - k** (assuming that Goldbach's conjecture is true), so the **0** in **p** won't lead to false positives.

In the loop, we update **k** and **m**. The new value of **m** is **m × k² = (k - 1)!² × k² = k!²**, and the new value of **k** is **k + 1**, so **m = (k - 1)!²** still holds before and after the update.

Then, we perform set union to add the value of **m % k × k** to **p**. By the corollary of Wilson's theorem, this will add **1 × k = k** if **k** is prime and **0 × k = 0** if not.

When the loop ends, we print the last values of **n - k** and **k**, which will be primes with sum **n**.
> 7 votes

# Answer
# Ruby 2.0 (65)

```
require'prime'
n=gets.to_i
Prime.find{|i|p [i,n-i]if(n-i).prime?}

```
> 5 votes

# Answer
## PHP - 73 bytes

```
<?for(;@($n%--$$n?:$o=&$argv[1]>$$n=++$n)||${++$b}^${--$o};);echo"$b+$o";

```

Input is taken as a command line argument.

Sample usage:

```
$ php goldbach.php 7098
19+7079

```
> 4 votes

# Answer
## GolfScript ~~41~~ ~~33~~ 32

```
~(,2>.-1%]zip{{.,2>\{\%!}+,},!}?

```

Accepts command line argument e.g.

```
echo "14" | ruby golfscript.rb goldbach.gs
-> [2 12]

```

Finds all relevant partitions of the input number with:

```
(,2>.-1%]zip  #If only zip were a one-character command!  It is so often useful.

```

and then finds the first partition where no numbers are NOT prime with:

```
{np,!}? #For each partition, filter down to elements that are not prime, and only accept if there are no such results (since [] is falsey).

```

where the composite-checking block `np` is:

```
{.,2>\{\%!}+,}

```

this block filters down to all numbers that evenly divide a given number. If there are no such numbers (so the number is prime), the result is `[]`, which is falsey in GolfScript.
> 4 votes

# Answer
### R, ~~170~~ ~~112~~ 83 characters

```
a=scan();b=2:a;p=b[rowSums(!outer(b,b,`%%`))<2];q=p[(a-p)%in%p][1];cat(a,":",q,a-q)

```

Indented:

```
a=scan() #Take user input as a numeric
b=2:a
p=b[rowSums(!outer(b,b,`%%`))<2] #Find all primes from 2 to user input
q=p[(a-p)%in%p][1] #Check which a-p also belong to p and takes the first one
cat(a,":",q,a-q)

```

Usage:

```
> a=scan();b=2:a;p=b[rowSums(!outer(b,b,`%%`))<2];q=p[(a-p)%in%p][1];cat(a,":",q,a-q)
1: 72
2:
Read 1 item
72 : 5 67

```

**Old solution at 112 characters, for posterity**

```
a=scan();b=2:a;p=b[rowSums(!outer(b,b,`%%`))<2];w=which(outer(p,p,`+`)==a,T);cat(a,":",p[w[1,1]],p[w[1,2]])

```

Indented:

```
a=scan()
b=2:a
p=b[rowSums(!outer(b,b,`%%`))<2]
w=which(outer(p,p,`+`)==a,T) #Find the index of valid combinations
cat(a,":",p[w[1,1]],p[w[1,2]]) #Prints the first valid combination

```
> 3 votes

# Answer
## perl 6: 69

```
$/=get;for grep &is-prime,^$/ {exit say $_,$_-$/ if ($/-$_).is-prime}

```
> 3 votes

# Answer
## JavaScript (ES6) (Regex), 105

```
a=/^(xx+?)(?!(xx+)\2+$)x*(?=\1$)(?!(xx+)\3+$)/.exec("x".repeat(prompt()));alert(a[1].length+"+"+a[0].length)

```

Now you have a regex that tests the Goldbach conjecture, which has low requirement on special features (basic back-reference support, positive and negative look-ahead).

This uses `String.prototype.repeat()`, which is part of EcmaScript 6th edition proposal. Currently, this code only works on Firefox.

I really need a better language that has terse command when working with regex...
> 3 votes

# Answer
# Python - 107

Basically an improvement on the second part of nutria's answer (I ran this on 2.7 but I think it should also work for 3.x)

```
p=lambda x:all(x%i!=0 for i in range(2,x))
n=input()
for i in range(2,n-1):
    if p(i)&p(n-i): print i,n-i

```
> 3 votes

# Answer
## Scala, ~~286~~ ~~192~~ ~~172~~ 148 chars

Not the fastest but it works. Call g(10) to obtain the list of goldbach pairs for 10.

```
def g(n:Int)={def p(n:Int,f:Int=2):Boolean=f>n/2||n%f!=0&&p(n,f+1)
s"$n : "+(for(i<-2 to n/2;j=n-i if p(i)&&p(j))yield s"$i + $j").mkString(" or ")}

```

Conversion to C++ is straightforward.
> 2 votes

# Answer
### newLISP - 169 148 chars

```
(define(p n)(=(length(factor n))1))
(define(g n)(when(even? n)(for(i 3 n 2)
(and(p i)(p(- n i))(println n {: } i { }(- n i))))))
(g(int(read-line)))

```

includes the code to run it. The results are over-generous...

```
72: 5 67
72: 11 61
72: 13 59
72: 19 53
72: 29 43
72: 31 41
72: 41 31
72: 43 29
72: 53 19
72: 59 13
72: 61 11
72: 67 5

```
> 2 votes

# Answer
# C - 139 129 characters

```
a,b;i(x,y){return x>y?x%y?i(x,y+1):0:x>1;}main(){scanf("%i",&a);for(b=a/2;b-->1;)i(b,2)&&i(a-
b,2)&&printf("%i:%i+%i\n",a,b,a-b);}

```
> 2 votes

# Answer
## Sage, ~~65~~ 62

```
n=input()
i=0
p=is_prime
while p(i)*p(n-i)==0:i+=1
print i,n-i

```

With the above in file `goldbach.sage`, execute it with Sage running in a terminal:

```
sage: %runfile goldbach.sage

```

Thanks to @boothby for the `p=is_prime` idea.
> 2 votes

# Answer
# Mathematica 56

This returns all of the solutions for the input integer.

```
Select[Tuples[Prime@Range@PrimePi[n = Input[]], 2], Tr@# == n &]

```

For example, when 1298 is input…

> {{7, 1291}, {19, 1279}, {61, 1237}, {67, 1231}, {97, 1201}, {127, 1171}, {181, 1117}, {211, 1087}, {229, 1069}, {277, 1021}, {307, 991}, {331, 967}, {379, 919}, {421, 877}, {439, 859}, {487, 811}, {541, 757}, {547, 751}, {571, 727}, {607, 691}, {691, 607}, {727, 571}, {751, 547}, {757, 541}, {811, 487}, {859, 439}, {877, 421}, {919, 379}, {967, 331}, {991, 307}, {1021, 277}, {1069, 229}, {1087, 211}, {1117, 181}, {1171, 127}, {1201, 97}, {1231, 67}, {1237, 61}, {1279, 19}, {1291, 7}}

As written, it returns each solution twice.

```
Union[Sort/@ %]

```

> {{7, 1291}, {19, 1279}, {61, 1237}, {67, 1231}, {97, 1201}, {127, 1171}, {181, 1117}, {211, 1087}, {229, 1069}, {277, 1021}, {307, 991}, {331, 967}, {379, 919}, {421, 877}, {439, 859}, {487, 811}, {541, 757}, {547, 751}, {571, 727}, {607, 691}}
> 2 votes

# Answer
## Sage, 60

Similar in score and feel to r.e.s.'s solution, but I think it's different enough to post.

```
i=n=input()
while not{i,n-i}<set(primes(n)):i-=1
print i,n-i

```
> 2 votes

# Answer
Haskell, 97C

```
g n=head[(a,b)|let q=p n,a<-q,b<-q,a+b==n]
p n=filter c[2..n]
c p=null[x|x<-[2..p-1],p`mod`x==0]

```

Explanation:

* `g` is the "goldbach" function. Calling `g n` gives you the pair of primes that add up to `n`.
* `p` is a function that generates a list of primes less than `n`.
* `c` is the prime checker function used to define `p`.

Example runs:

```
*Main> g 4
(2,2)
*Main> g 6
(3,3)
*Main> g 8
(3,5)
*Main> g 10
(3,7)
*Main> g 12
(5,7)
*Main> map g [4,6..100]
[(2,2),(3,3),(3,5),(3,7),(5,7),(3,11),(3,13),(5,13),(3,17),(3,19),(5,19),(3,23),(5,23),(7,23),(3,29),(3,31),(5,31),(7,31),(3,37),(5,37),(3,41),(3,43),(5,43),(3,47),(5,47),(7,47),(3,53),(5,53),(7,53),(3,59),(3,61),(5,61),(7,61),(3,67),(5,67),(3,71),(3,73),(5,73),(7,73),(3,79),(5,79),(3,83),(5,83),(7,83),(3,89),(5,89),(7,89),(19,79),(3,97)]

```
> 2 votes

# Answer
# Julia, ~~50~~ 49 bytes

```
~=primes;n=ARGS[]|>int
(n-~n)∩~n|>extrema|>show

```

Try it online!

If a function were acceptable, the code could be shortened to **32 bytes**:

```
~=primes
!n=(n-~n)∩~n|>extrema

```

### How it works

`~=primes` creates an alias for the built-in **primes** function which returns a list of all prime numbers up to its argument. `n=ARGS[]|>int` parses the first command-line argument as saves it in **n**.

To find a suitable pair of primes, we first compute the aforementioned prime range with `~n`. Then, `n-~n` yields all differences of these primes and **n**.

By intersecting () the result with the prime range itself, we make sure that the remaining primes **p** are such that **n - p** is also a prime.

Finally, `extrema` takes the lowest and highest prime in the intersection, so their sum must be **n**.
> 2 votes

# Answer
## Python 3 - ~~150~~ 143 characters

Old version (150 characters):

```
p=lambda n:0 in[n % i for i in range(2,n)]
n=int(input())
[print('%d+%d'%(a, b))for b in range(2,n)for a in range(2,n)if not(a+b!=n or p(a) or p(b))]

```

New version (thanks to ProgramFOX):

```
p=lambda n:0 in[n%i for i in range(2,n)]
n=int(input())
[print('%d+%d'%(a,b))for b in range(2,n)for a in range(2,n)if not((a+b!=n)|p(a)|p(b))]

```

It prints every combination, for example:
4 2+2
10 7+3 5+5 3+7
> 1 votes

# Answer
# JavaScript, ~~139~~ ~~137~~ 136

```
a=prompt();function b(n){for(i=2;i<n;i++)if(n%i<1)return;return 1}for(c=2,r=1;c<a&&r;c++)if(b(c)&&b(a-c))alert(a+": "+c+" + "+(a-c)),r=0

```
> 1 votes

# Answer
# Julia, 62 Chars (85 with prompt)

```
julia> g(n)=collect(filter((x)->sum(x)==n,combinations(primes(n),2)))
g (generic function with 1 method)

julia> g(88)
4-element Array{Array{Int64,1},1}:
 [5,83]
 [17,71]
 [29,59]
 [41,47]

```
> 1 votes

# Answer
## GTB, 31

*For your TI-84 Calculator*

```
`A:.5A→B@%;A,4)4$~B+1,B-1#~B,B&

```

No prime built-ins.

**Example runs**

```
?4
               2
               2
?6
               3
               3
?8
               3
               5
?10
               5
               5

```
> 1 votes

# Answer
# q \[116 chars\]

```
y where all each{{2=count where 0=(x mod)each til x+1}each x}each y:{a where x=sum each a:a cross a:til x}"I"$read0 0

```

No inbuilt function to find prime number.

Input

```
72

```

Output

```
5  67
11 61
13 59
19 53
29 43
31 41
41 31
43 29
53 19
59 13
61 11
67 5

```
> 1 votes

# Answer
# J - ~~35~~ 32 char

"Prompt the user" is the bane of every J golfer. There go all my hard-earned characters!

```
p:(n,n)#:i.&n,+/~p:i.n=:".1!:1]1

```

Explained:

* `".1!:1]1` \- Read in a string (`1!:1`) from input (file handle `1`) and convert it to a number (`".`).
* `p:i.n=:` \- Assign this number to the variable `n`, and then take the first `n` primes.
* `+/~` \- Make an addition table, `n` wide and `n` high.
* `i.&n,` \- Turn the table into a single list, and then find the index of the first occurrence of `n`, which exists if Goldbach's conjecture is true.
* `p:(n,n)#:` \- Retrieve the row and column from the index, and take the corresponding primes.

Usage:

```
   p:(n,n)#:i.&n,+/~p:i.n=:".1!:1]1
666
5 661
   p:(n,n)#:i.&n,+/~p:i.n=:".1!:1]1
1024
3 1021

```

Had the prompt not been a requirement, here's a 25 character verb:

```
(,~p:@#:]i.~&,+/~@:p:@i.)

```
> 1 votes

# Answer
## Python - 206

A little late to the party but I am practicing my golfing skills.

I actually coded this before I found this question! So mine doesn't include the beautiful lambda that the other Python solutions use.

```
import math
def p(n):
    if n%2==0&n>2:return False
    for i in range(3,n):
        if n%i==0:return False
    return True
X=int(input())
for i in range(2,X):
    if p(i)&p(X-i):print i,X-i;break

```
> 1 votes

# Answer
# Jelly, 8 bytes (non-competing)

```
_ÆRfÆR.ị

```

Try it online! or verify all test cases.

### How it works

```
_ÆRfÆR.ị  Main link. Argument: n (integer)

 ÆR       Prime range; yield all primes in [1, ..., n].
_         Subtract all primes from n.
   fÆR    Filter; intersect the list of differences with the prime range.
      .ị  At-index 0.5; yield the last and first element.

```
> 1 votes

# Answer
Python3 version of this one -110 bytes

```
p=lambda x:all(x%i!=0 for i in range(2,x))
n=int(input())
for i in range(2,n-1):
 if p(i)&p(n-i): print(i,n-i)

```

and a super golfed version:

```
exec(bytes('㵰慬扭慤砠愺汬砨椥㴡‰潦⁲湩爠湡敧㈨砬⤩渊椽瑮椨灮瑵⤨਩潦⁲湩爠湡敧㈨測ㄭ㨩 晩瀠椨☩⡰⵮⥩›牰湩⡴Ⱪ⵮⥩','u16')[2:])

```
> 1 votes

# Answer
## Batch - 266

```
@echo off&setLocal enableDelayedExpansion&for /L %%a in (2,1,%1)do (set/aa=%%a-1&set c=&for /L %%b in (2,1,!a!)do set/ab=%%a%%%%b&if !b!==0 set c=1
if !c! NEQ 1 set l=!l!%%a,)&for %%c in (!l!)do for %%d in (!l!)do set/ad=%%c+%%d&if !d!==%1 set o=%%c + %%d
echo !o!

```

Set out neatly -

```
@echo off
setLocal enableDelayedExpansion
for /L %%a in (2,1,%1) do (
    set /a a=%%a-1
    set c=
    for /L %%b in (2,1,!a!) do (
        set /a b=%%a%%%%b
        if !b!==0 set c=1
    )
    if !c! NEQ 1 set l=!l!%%a,
)
for %%c in (!l!) do for %%d in (!l!) do (
    set /a d=%%c+%%d
    if !d!==%1 set o=%%c + %%d
)
echo !o!

```
> 0 votes

# Answer
# SQL, ~~295~~ 284

In postgresql:

```
create function c(c int) returns table (n int, m int) as $$
with recursive i(n) as
(select 2 union all select n+1 from i where n<c),
p as (select * from i a where not exists
(select * from i b where a.n!=b.n and mod(a.n,b.n)=0))
select * from p a, p b where a.n+b.n=c
$$ language sql;

```

Should be able to do it in half the space though, if it weren't for things like "no left outer join in recursion", "no subquery in recursion"...

Here's the output:

```
postgres=# select c(10);
   c
-------
 (3,7)
 (5,5)
 (7,3)
(3 rows)

postgres=# select c(88);
   c
---------
 (5,83)
 (17,71)
 (29,59)
 (41,47)
 (47,41)
 (59,29)
 (71,17)
 (83,5)
(8 rows)

```
> 0 votes

# Answer
## Perl 5, 58 bytes

57, plus 1 for `-nE`

```
/^(11+?)(?!(11+)\2+$)1*(?=\1$)(?!(11+)\3+$)/;say for$1,$&

```

Input and output are in unary. Example:

```
$ perl -nE'/^(11+?)(?!(11+)\2+$)1*(?=\1$)(?!(11+)\3+$)/;say for$1,$&'
1111111111
111
1111111

```

Hat-tip.
> 0 votes

# Answer
# Oracle SQL 11.2, 202 bytes

```
WITH v(x,y,s)AS(SELECT LEVEL,LEVEL,0 FROM DUAL CONNECT BY LEVEL<=:1 UNION ALL SELECT x,y-1,s+SIGN(MOD(x,y))FROM v WHERE y>1),p AS(SELECT x FROM v WHERE x-s=2)SELECT a.x,b.x FROM p a,p b WHERE:1=a.x+b.x;

```

Un-golfed

```
WITH v(x,y,s) AS
(
  SELECT LEVEL,LEVEL,0 FROM DUAL CONNECT BY LEVEL<=:1
  UNION ALL
  SELECT x,y-1,s+SIGN(MOD(x,y))FROM v WHERE y>1
)
,p AS (SELECT x FROM v WHERE x-s=2)
SELECT a.x,b.x
FROM p a,p b
WHERE :1=a.x+b.x;

```
> 0 votes

# Answer
## Python 3, 107 bytes

```
b=lambda x:all(x%y for y in range(2,x))
g=lambda x,i=2:((i,x-i)if b(i)&b(x-i)else g(x,i+1))if(i<x)else 0

```

b(x) is a primality test for x, and g(x) recurses through numbers to find two primes that fit.
> 0 votes

# Answer
# 05AB1E, 12 bytes

```
ÅP©-ʒ®så}Á2£

```

Try it online!
> 0 votes

# Answer
# Thunno 2, 7 bytes

```
œP2ṚæS:

```

Try it online!

Prints all possible pairs. If you only want one, add the `h` flag.

#### Explanation

```
œP2ṚæS:  # Implicit input
œP       # Filter [1..input] for primes
   Ṛ     # Combinations with replacement
  2      # with a length of two
    æS:  # Filter by sum equals input
         # Implicit output

```
> 0 votes

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


# Question
Title: The program that will find the next prime number
# Intro:

---

You accidentally corrupted the flow of time with a device you made for fun, that turned out to be a time machine. As a result, you got pushed to the far future. You realized that computing, processing power, and computers in general have been evolved by a huge amount, *an infinite amount to be precise*. So you grab yourself a computer with infinite memory and processing power. You have no idea how it can have infinite memory and infinite processing power, but you just accept it and return to the present.

## Challenge:

---

You heard that the person who discovered the currently largest prime `2^74,207,281 − 1` got paid $100.000. You decide to make a program that finds the next prime, since you want to get back the money you spent for the computer. You make one that takes input of a number, and finds the next prime number, either by bruteforcing or any other method.

**Clarifications:** You have a hypothetical machine with infinite memory and processing power. Your program MUST NOT be limited (e.g.: C#'s int's can store from `-2,147,483,648` to `2,147,483,647`), well your program must be able to store, and work with any number of any size. You have infinite resources, so you shouldnt care if you would run out of memory if you allowed that.

**Example I/O:**
Input: The currently largest discovered prime with 22,338,618 digits.
Output: Exactly the next prime

Obviously, you dont have to prove that it works, as it would take a ton of time to compute in a physical machine. But if you moved your program to a hypothetical machine with infinite processing power / memory, it should compute instantly.

---

Finding the next prime and checking if a number is a prime, are two completely different things

# Answer
> 24 votes
# Mathematica, 9 bytes

```
NextPrime

```

# Answer
> 13 votes
# Python 3, 45 bytes

```
f=lambda n,k=1,m=1:m%k*k>n or-~f(n,k+1,m*k*k)

```

Try it online!

# Answer
> 7 votes
## Python 2, ~~78~~ ~~77~~ ~~76~~ 74 bytes

```
def f(n):
 while 1:
    n+=1
    if[i for i in range(1,n)if n%i<1]==[1]:return n

```

---

-1 byte thanks to @KritixiLithos
-1 byte thanks to @FlipTack
-2 bytes thanks to @ElPedro

# Answer
> 7 votes
# Regex  (PCRE2 v10.35 or later), ~~80~~ 77 bytes

```
^(?=(?*(x+?)(x*$))(?!(?*(xx+)(x+$))(?=\3*(x+))(?=\4\5(x*))\6\2\3*$))\2x+|\B|$

```

Attempt This Online!

Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)

This is the first -regex I've written that can be really said to compute its result before turning it into a number of possible matches. This output method allows actually directly returning the result; before adopting this output method, it was impossible for a regex to return a value greater than the input.

The regex computes \\$p-n\\$, where \\$n\\$ is the input and \\$p\\$ is the next prime. To do this it takes advantage of the fact that there will always be a prime in the interval \\$(n,2n\]\\$. Once that is complete, it outputs \\$p-n+n=p\\$ in the form of a number of possible matches.

```
    ^                    # tail = N = input number
    (?=
        (?*              # Non-atomic lookahead (try all options until matching)
            (x+?)(x*$)   # \1 = conjectured P - N; \2 = N - \1
        )
        (?!              # Negative lookahead - assert that this cannot match
            (?*          # Non-atomic lookahead (try all options until matching)
                (xx+)    # \3 = try all numbers from 2 through N-1
                (x+$)    # \4 = N - \3; assert \3 < N
            )
            (?=          # Atomic lookahead (locks onto the first match)
                \3*(x+)  # \5 = N % \3, giving \3 instead of 0
            )
            (?=          # Atomic lookahead (locks onto the first match)
                \4       # head = \4
                \5       # head += \5
                (x*)     # \6 = tail == N - head == tool to make tail = \4 + \5
            )
            \6           # tail = tail-\6 == \4 + \5
            \2           # tail -= \2
            \3*$         # Assert tail is divisible by \3
        )
    )
    \2                   # tail = \1
    x+                   # add tail to the number of possible matches
|
    \B                   # add abs(N-1) to the number of possible matches
|
    $                    # add 1 to the number of the possible matches; this gets
                         # us a return value of 2 for N==0, instead of 0 which we
                         # would have if simply adding N instead of abs(N-1)+1

```

Molecular lookahead `(?*`...`)` is used for convenience. It would be possible to port to flavors that don't have it, but the regex would be much longer – it would still need to emulate arithmetic in the range \\$\[0,2n\]\\$, but would need to do so within just \\$\[0,n/4\]\\$ or perhaps \\$\[0,n/3\]\\$, instead of \\$\[0,n\]\\$ as this version does.

Without returning the correct value for \\$0\\$, this would be **72 bytes**.

# Regex  (.NET), 79 bytes

```
(?=(x)*)((?<1>x)+?)(x*$)(?<!(?=(?=\6*(x+))\5\4(?<=^\3\6*))(^x+)(x+x))|(?<1>){2}

```

Try it online!

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

```
                           # tail = N = input number
    (?=(x)*)               # \1.captureCount = N
    ((?<1>x)+?)(x*$)       # Assert N > 0; \2 = P - N;
                           # \1.captureCount += \2; \3 = N - \2
    (?<!                   # Right-to-left negative lookbehind
        (?=                # Atomic lookahead
            (?=            # Atomic lookahead
                \6*(x+)    # \4 = N % \6, giving \6 instead of 0
            )
            \5             # head = \5
            \4             # head += \4
            (?<=           # Right-to-left atomic lookbehind
                ^\3\6*     # Assert head-\3, that is, \5+\4-\3, is divisible by \6
            )
        )
        (^x+)              # \5 = N - \6; assert \6 < N
        (x+x)              # \6 = try all numbers from 2 through N-1
    )
|
    (?<1>){2}              # if N == 0, \1.captureCount = 2

```

Without returning a value for \\$0\\$, this would be **69 bytes**.

# Answer
> 6 votes
# Jelly, 2 bytes

```
Æn

```

Try it online!

This implicitly takes input z and, according to the manual, generate the closest prime strictly greater than z.

# Answer
> 4 votes
# Oasis, 2 bytes

Run with the **`-n`** flag.

Code:

```
p

```

Try it online!

# Answer
> 4 votes
# Bash \+ coreutils, 52 bytes

```
for((n=$1,n++;`factor $n|wc -w`-2;n++)){ :;};echo $n

```

Try it online!

The documentation for bash and factor do not specify a maximum integer value they can handle (although, in practice, each implementation does have a maximum integer value). Presumably, in the GNU of the future on your infinitely large machines, bash and factor will have unlimited size integers.

# Answer
> 3 votes
# Maxima, 10 bytes

```
next_prime

```

A function returns the smallest prime bigger than its argument.

# Answer
> 3 votes
# Python with sympy, 28 bytes

```
import sympy
sympy.nextprime

```

`sympy.nextprime` is a function which does what it says on the tin. Works for all floats.

**repl.it**

---

# Python, ~~66~~ 59 bytes

-4 bytes thanks to Lynn (use `-~`)
-3 bytes thanks to FlipTack (use `and` and `or`, allowing `...==1` to be switched to a `...-1` condition.)

```
f=lambda n:sum(-~n%-~i<1for i in range(n))-1and f(n+1)or-~n

```

**repl.it**

A recursive function that counts up from `n` until a prime is found by testing that only one number exists up to `n-1` that divides it (i.e. 1). Works for all integers, raises an error for floats.

Works on 2.7.8 and 3.5.2, does not work on 3.3.3 (syntax error due to lack of space between `==1` and `else`)

# Answer
> 3 votes
# Brachylog, 2 bytes

```
<ṗ

```

Try it online!

### Explanation

```
(?) <   (.)      Input < Output
      ṗ (.)      Output is prime
                 (Implicit labelization of the Output at the end of the predicate)

```

# Answer
> 2 votes
## Pyke, ~~8~~ 7 bytes

```
~p#Q>)h

```

Try it here!

### 4 bytes, noncompeting

(Interpreter updated since challenge posted)

```
~p<h

```

Try it here!

```
~p   -   primes_iterator()
  <  -  filter(^, input() < i)
   h - ^[0]

```

# Answer
> 2 votes
# Python, ~~114~~ 83 bytes

```
def g(b):
 while 1:
  b+=1
  for i in range(2,b):
   if b%i<1:break
  else:return b

```

Without builtins, if there are any.

-30 by removing whitespace and -1 by changing `b%i==0` to `b%i<1`

# Answer
> 2 votes
# Perl 6, 25 bytes

```
{first *.is-prime,$_^..*}

```

### How it works

```
{                       }  # A lambda.
                  $_ ..*   # Range from the lambda argument to infinity,
                    ^      # not including the start point.
 first           ,         # Iterate the range and return the first number which
       *.is-prime          # is prime.

```

---

# Perl 6, 32 bytes

```
{first {all $_ X%2..^$_},$_^..*}

```

With inefficient custom primality testing.

### How it works

Outer structure is the same as above, but the predicate passed to `first` (to decide if a given number is prime), is now:

```
{               }  # A lambda.
     $_            # Lambda argument (number to be tested).
          2..^$_   # Range from 2 to the argument, excluding the end-point.
        X          # Cartesian product of the two,
         %         # with the modulo operator applied to each pair.
 all               # Return True if all the modulo results are truthy (i.e. non-0).

```

# Answer
> 2 votes
# Lua, 876 Bytes

```
function I(a)a.s=a.s:gsub("(%d)(9*)$",function(n,k)return tostring(tonumber(n)+1)..("0"):rep(#k)end)end function D(a)a.s=a.s:gsub("(%d)(0*)$",function(n,k)return tostring(tonumber(n)-1)..("9"):rep(#k)end):gsub("^0+(%d)","%1")end function m(a,b)local A=K(a)local B=K(b)while V(0,B)do D(A)D(B)end return A end function M(a,b)local A=K(a)local B=K(b)while V(m(B,1),A)do A=m(A,B)end return A end function l(n)return#n.s end function p(a)local A=K(a)local i=K(2)while V(i,A)do if V(M(A,i),1)then return false end I(i)end return true end function V(b,a)A=K(a)B=K(b)if l(A)>l(B)then return true end if l(B)>l(A)then return false end for i=1,l(A)do c=A.s:sub(i,i)j=B.s:sub(i,i)if c>j then return true elseif c<j then return false end end return false end function K(n)if(type(n)=='table')then return{s=n.s}end return{s=tostring(n)}end P=K(io.read("*n"))repeat I(P)until p(P)print(P.s)

```

Lua, unlike some other languages, does have a Maximum Integer Size. Once a number gets larger than 232, things stop working correctly, and Lua starts trying to make estimates instead of exact values.

As such, I had to implement a new method of storing numbers, in particular, I've stored them as Base10 strings, because Lua doesn't have a size limit on Strings, other than the size of the memory.

I feel this answer is much more to the Spirit of the question, as it has to itself implement arbitrary precision integers, as well as a prime test.

## Explained

```
-- String Math
_num = {}

_num.__index = _num

-- Increase a by one.
-- This works by grabbing ([0-9])999...$ from the string.
-- Then, increases the first digit in that match, and changes all the nines to zero.
-- "13", only the "3" is matched, and it increases to 1.
-- "19", firstly the 1 is turned to a 2, and then the 9 is changed to a 0.
-- "9" however, the 9 is the last digit matched, so it changes to "10"
function _num.inc(a)
    a.str = a.str:gsub("(%d)(9*)$",function(num,nines)
            return tostring(tonumber(num)+1)..("0"):rep(#nines)
        end)
end

-- Decrease a by one
-- Much like inc, however, uses ([0-9])0...$ instead.
-- Decrements ([0-9]) by one and sets 0... to 9...
-- "13" only the "3" is matched, and it decreases by one.
-- "10", the "1" is matched by the ([0-9]), and the 0 is matched by the 0..., which gives 09, which is clipped to 9.
function _num.dec(a)
    a.str = a.str:gsub("(%d)(0*)$",function(num,zeros)
        return tostring(tonumber(num)-1)..("9"):rep(#zeros)
    end)         :gsub("^0+(%d)","%1")
end

-- Adds a and b
-- Makes A and B, so that the original values aren't modified.
-- B is then decremented until it hits 0, and A is incremented.
-- A is then returned.
function _num.__add(a,b)
    local A = str_num(a)
    local B = str_num(b)
    while B > 0 do
        A:inc()
        B:dec()
    end
    return A
end

-- Subs b from a
-- Works just like Addition, yet Dec's A instead of Incs.
function _num.__sub(a,b)
    local A = str_num(a)
    local B = str_num(b)
    while B > 0 do
        A:dec()
        B:dec()
    end
    return A
end

-- A % B
-- Makes A and B from a and b
-- Constantly subtracts B from A until A is less than B
function _num.__mod(a,b)
    local A = str_num(a)
    local B = str_num(b)
    while A >= B do
        A = A - B
    end
    return A
end

-- #a
-- Useful for golfiness
function _num.__len(n)
    return #n.str
end

-- Primacy Testing
-- Generates A from a and i from 2.
-- Whilst i is less than A, i is incremented by one, and if A % i == 0, then it's not a prime, and we return false.
-- Once that finishes, we return true.
function _num.isprime(a)
    local A = str_num(a)
    local i = str_num(2)
    while i < A do
        if A%i < 1 then
            return false
        end
        i:inc()
    end
    return true
end

-- b < a
-- A and B are generated from a and b
-- Fristly, if the length of A and B aren't equal, then that result is output.
-- Otherwise, each character is searched from left to right, the moment they are unequal, the difference is output.
-- If all the characters match, then it's equal. Return false.
function _num.__lt(b,a)
    A=str_num(a)
    B=str_num(b)
    if #A > #B then
        return true
    end
    if #B > #A then
        return false
    end
    for i=1, #A.str do
        As = A.str:sub(i,i)
        Bs = B.str:sub(i,i)
        if As > Bs then
            return true
        elseif As < Bs then
            return false
        end
    end
    return false
end

-- b <= a
-- Same as b < a, but returns true on equality.
function _num.__le(b,a)
    A=str_num(a)
    B=str_num(b)
    if #A > #B then
        return true
    end
    if #B > #A then
        return false
    end
    for i=1, #A.str do
        As = A.str:sub(i,i)
        Bs = B.str:sub(i,i)
        if As > Bs then
            return true
        elseif As < Bs then
            return false
        end
    end
    return true
end

-- Just straight up returns it's string component. Endlessly faster than the int equivalent, mostly because it never is anything _but_ the string form.
function _num.__tostring(a)
    return a.str
end

-- Just set up the metatable...
function str_num(n)
    if(type(n)=='table')then
        return setmetatable({str = n.str}, _num)
    end
    return setmetatable({str = tostring(n)}, _num)
end

-- Generate a new str_num from STDIN
Prime = str_num(io.read("*n"))

-- This is handy, because it will call Prime:inc() atleast once, and stop at the next prime number it finds.
-- Basically, if it weren't for all that overhead of making the math possible, that's all this would be.
repeat
    Prime:inc()
until Prime:isprime()
print(Prime)

```

Although the above uses Metatables, instead of just regular functions like the actual answer, which worked out smaller.

# Answer
> 2 votes
# Vyxal, 2 bytes

```
∆Ṗ

```

Try it Online!

Here for completeness. Like answers in many other golfing langs, `∆Ṗ` is simply a builtin for "next prime greater than n". It uses `sympy.nextprime` from Python's `sympy` library to do this

# Answer
> 1 votes
# J, 4 bytes

```
4&p:

```

Simple built in for next prime.

# Answer
> 1 votes
# 05AB1E, ~~16~~ 13 bytes (Emigna @ -3 bytes)

```
2•7£?ÿ•o[>Dp#

```

Try it online!

```
2•7£?ÿ•o        # Push current largest prime.
        [   #    # Until true..
         >Dp    # Increment by 1, store, check primality.
                # After infinite loop, implicitly return next prime.

```

# Answer
> 1 votes
# Java 7, ~~373~~ ~~343~~ ~~334~~ ~~303~~ 268 bytes

```
import java.math.*;class M{public static void main(String[]a){BigInteger n,i,o,r=new BigInteger(a[0]);for(r=r.add(o=r.ONE);;r=r.add(o)){for(n=r,i=o.add(o);i.compareTo(n)<0;n=n.mod(i).compareTo(o)<0?r.ZERO:n,i=i.add(o));if(n.compareTo(o)>0)break;}System.out.print(r);}}

```

-75 bytes thanks *@Poke*

**Ungolfed:**

```
import java.math.*;
class M{
  public static void main(String[] a){
    BigInteger n,
               i,
               o,
               r = new BigInteger(a[0]);
    for(r = r.add(o = r.ONE); ; r = r.add(o)){
      for(n = r, i = o.add(o); i.compareTo(n) < 0; n = n.mod(i).compareTo(o)< 0
                                                        ? r.ZERO
                                                        : n,
                                                   i = i.add(o));
      if(n.compareTo(o) > 0){
        break;
      }
    }
    System.out.print(r);
  }
}

```

Try it here.

**Some example input/outputs:**

```
7 -> 11
1609 -> 1613
104723 -> 104729

```

# Answer
> 1 votes
## Perl, 30 bytes (29 +1 for `-p`):

```
(1x++$_)=~/^(11+?)\1+$/&&redo

```

**Usage**

Input the number after pressing return (input 12345 in example below, outputs 12347):

```
$ perl -pe '(1x++$_)=~/^(11+?)\1+$/&&redo'
12345
12347

```

**How it works**

* Define a string of `1`'s that has length `++$_`, where `$_` is initially the input value
* The regex checks to see if the string of `1`s is non-prime length (explained here).
* If the string length is non-prime, the check is re-evaluated for the next integer (`++$_`)
* If the string length is prime, the implicit `while` loop exits and `-p` prints the value of `$_`
* Note: there is no need to handle the edge case `"1"` of length 1 because it will never be used for values less than `1`, per the specification.

# Answer
> 1 votes
# 05AB1E, 2 bytes

```
ÅN

```

Try it online!

```
ÅN  # full program
ÅN  # push smallest prime greater than...
    # implicit input
    # implicit output

```

# Answer
> 1 votes
# Pyth, 5 bytes

```
fP_Th

```

Try it online!

---

Explanation:

```
f      # first integer greater than or equal to
    hQ # input + 1
 P_T   # which is prime

```

# Answer
> 1 votes
# Husk, ~~4~~ 3 bytes

*Edit: -1 byte thanks to Leo*

```
ḟṗ→

```

Try it online!

```
ḟ     # first element that
 ṗ    # is a prime,
  →   # counting up beginning at one greater than the input

```

# Answer
> 1 votes
## Java, 176 Bytes

```
import java.math.*;import java.util.*;class a{public static void main(String[] args){System.out.print(new BigInteger(new Scanner(System.in).nextLine()).nextProbablePrime());}}

```

# Answer
> 1 votes
# Vyxal, 40 bits1, 5 bytes

```
{›:æ¬|

```

Try it Online!

Non-built-in answer, but does use a prime check built-in

## Explained

```
{›:æ¬|
{    | # While
 ›     # incrementing the top of the stack
  :æ¬  # gives a non prime number:
       #  do nothing. just run the condition actually.

```

## Vyxal, 52 bits1, 6.5 bytes

```
{›:KḢ₃¬|

```

Try it Online!

Uses `KḢ₃` as a prime check (`len(factors(x)[1:] == 1`)

# Answer
> 1 votes
# Nekomata `-1`, 3 bytes

```
Ƥ$>

```

Attempt This Online!

#### Explanation

```
Ƥ$>  # Implicit input
Ƥ    # Find the first prime
  >  # which is greater than
 $   # the input integer
     # Implicit output

```

# Answer
> 1 votes
# Thunno 2, 3 bytes

```
µƘP

```

Try it online!

#### Explanation

```
µƘP  # Implicit input
µƘ   # Find the next number after the input
  P  # which is a prime number
     # Implicit output

```

# Answer
> 0 votes
## QBIC, 34 bytes

```
:{a=a+1[2,a/2|~a%b=0|b=a]]~a<b|_Xa

```

Based off this QBIC primality tester. Explanation:

```
:{a=a+1    Read 'a' from the command line, start an infinite loop
           and at the start of each iteration increment 'a'
[2,a/2|    FOR b = 2, b <= a/2, b++
~a%b=0|    IF b cleanly divides a, we're no prime
b=a]]      so, break out of the FOR loop ( ]] = End if, NEXT )
~a<b|      If the FOR loop completed without breaking
_Xa        then quit, printing the currently tested (prime) number
           The second IF and the DO-loop are implicitly closed by QBIC.

```

# Answer
> 0 votes
# JavaScript (ES7), 61 bytes

```
a=>{for(;a++;){for(c=0,b=2;b<a;b++)a%b||c++;if(!c)return a;}}

```

## Usage

```
f=a=>{for(;a++;){for(c=0,b=2;b<a;b++)a%b||c++;if(!c)return a;}}
f(2)

```

## Output

```
3

```

# Answer
> 0 votes
# MATL, 3 bytes

```
_Yq

```

The function `Yq` returns the next prime of the absolute value of the input if the input is negative so we implicitly grab the input, negate it (`_`) and find the next prime using `Yq`.

**Try it Online!**

# Answer
> 0 votes
# Haskell, ~~42~~ ~~46~~ 43 bytes

```
f n=[i|i<-[n..],all((>0).rem i)[2..i-1]]!!1

```

the usual code for brute force.

Of course this finds the next *smallest* prime number after `n`. There is no biggest prime.

Works for *n* \> *0*.

*edit:* Assumes `n` is prime. Thanks to @Laikoni's advice in the comments.

# Answer
> 0 votes
# Python + primefac, ~~34~~ 32 bytes

Not quite as short as using `sympy` (another answer already uses that), but it's still pretty short, and it's *much* faster.

```
import primefac as p
p.nextprime

```

**Try it online**

Input of `2**2000` completes in a couple seconds.

# Answer
> 0 votes
# SimpleTemplate, 132 bytes

The algorithm is terrible, since I have to do my own code to check if a number is prime or not.
It proved to be horrible, but works.

```
{@setY argv.0}{@setX 1}{@whileX}{@setX}{@set+T Y,-1}{@for_ from2 toT}{@ifY is multiple_}{@incX}{@/}{@/}{@ifX}{@incY}{@/}{@/}{@echoY}

```

Receives the number as the first argument, outputting the result.

---

**Ungolfed:**

```
{@set number argv.0}
{@set remainder 1}
{@while remainder}
    {@set remainder 0}
    {@set+ tmp number, -1}
    {@for divisor from 2 to tmp}
        {@if number is multiple divisor}
            {@inc by 1 remainder}
        {@/}
    {@/}
    {@if remainder}
        {@inc by 1 number}
    {@/}
{@/}
{@echo number}

```

Any tips on how to remove that last `@if`?

# Answer
> 0 votes
# Ruby, 28+6 = 34 bytes

Uses the `-rprime` flag.

```
f=->i{i+=1;i.prime??i :f[i]}

```

Non-recursive version for 31+6=37 bytes:

```
->i{i+=1;i+=1 while i.prime?;i}

```

# Answer
> 0 votes
# Japt, 6 bytes

```
_j}aUÄ

```

Run it online.

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