text:
Leaping Kangaroos
Backstory
Disclaimer: May contain made up information about kangaroos.
Kangaroos traverse several stages of development. As they grow older and stronger, they can jump higher and longer, and they can jump more times before they get hungry.
In stage 1, the kangaroo is very little and cannot jump at all. Despite this, is constantly requires nourishment. We can represent a stage 1 kangaroo's activity pattern like this.
o

In stage 2, the kangaroo can make small jumps, but not more than 2 before it gets hungry. We can represent a stage 2 kangaroo's activity pattern like this.
 o o
o o o

After stage 2 the kangaroo improves quickly. In each subsequent stage, the kangaroo can jump a bit higher (1 unit in the graphical representation) and twice as many times. For example, a stage 3 kangaroo's activity pattern looks like this.
  o   o   o   o
 o o o o o o o o
o   o   o   o   o

For stage n, the activity pattern consists of 2n-1 V-shaped jumps of height n.
For example, for stage 4, there are 8 jumps of height 4.
   o     o     o     o     o     o     o     o
  o o   o o   o o   o o   o o   o o   o o   o o
 o   o o   o o   o o   o o   o o   o o   o o   o
o     o     o     o     o     o     o     o     o

Task
Write a full program or a function that takes a positive integer n as input and prints or returns the ASCII art representation of a stage n kangaroo's activity pattern.
Surrounding whitespace and ANSI escape codes are allowed, as long as the pattern looks exactly as depicted above.
If you choose a function that returns the output, it must return a single string or character array that displays the proper output when printed. Returning an array of strings is not allowed.
You can use any printable, non-whitespace character instead of o, as long as it is consistent within the activity pattern and across all patterns in your answer.
This is code-golf; may the shortest answer in bytes win!

I need some clarification. You said you can use any character to represent o. Can you also use any character to represent the spaces (as long as they are different?)?

The spaces have to be blank. You can use actual spaces or you can use control codes to move the cursor around, but you cannot use printable non-space characters.

http://codegolf.stackexchange.com/questions/96379/compute-the-kangaroo-sequence - Related.

05AB1E, 12 10 bytes
Îj¹FÐvû},À

Explanation:
Î              # Push zero and input
 j             # Prepend input - 1 spaces
  ¹F           # Input times do..
    Ð          #   Triplicate the string
     v }       #   Length times do..
      û        #     Palindromize
        ,      #   Pop and print with a newline
         À     #   Rotate the string on to the right

Uses the CP-1252 encoding. Try it online!

Interesting, smarter than zip.

MATLAB, 92 90 86 84 bytes
n=input('');p=eye(n)+32;A=repmat([fliplr(p),p,''],1,2^n/2);A(:,n+1:n:end)=[];disp(A)

Try it online!
eye creates an identity matrix. If we flip it and concatenate the original i.e. [fliplr(p),p] we get (for n=3):
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1

With repmat(...,1,2^n/2) we repeat this 2^(n-1) times and get
0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0
0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 ...
1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1

From this we just delete the unnecessary columns, with A(:,n+1:n:end)=[];

Congrats on 20k!!

Thank you!

Charcoal, 14 bytes
ＮλＰ^×λoＦ⁻λ¹‖Ｏ→

Try it online!
Explanation
Ｎλ inputs an integer into λ. Ｐ^ is a multidirectional print (SE and SW) of ×λo (string multiplication of λ with o). Then Ｆ⁻λ¹ runs a for loop λ - 1 times, in which ‖Ｏ→ reflects the whole thing to the right with overlap.

"Ｐ^ is a multidirectional print (SE and SW)" Cool, that's something you don't see very often in programming languages!

Just leaving this here

Python 2, 83 81 bytes
n=input()
i=0
exec"s=' '*n+'o'+' '*i;i+=1;print(s[i:-1]+s[:i:-1])*2**~-n+s[i];"*n

Try it online!

Welcome to PPCG! Nice first post!

That's kind of an understatement; outgolfing xnor in Python is no small feat. I do see some room for improvement. A while loop should save a byte and the exec trick can save a few more.

Python 2, 87 bytes
n=input()
for i in range(n):print''.join(' o'[abs(j%(2*n)-n)==i]for j in range(1,n<<n))

Try it online!
Uses a formula for the coordinates (i,j) that contain a circle, then joins and prints the grid. There's a lot of golf smell here -- ''.join, two nested ranges, for over exec, so there's likely to be improvements.

Befunge, 98 91 bytes
This uses a , in place of the o, since that enables us to save a couple of bytes.
&::1>\1-:v
+\:v^*2\<_$\1-2*::!+00p*1
:-1_@v0\-g01:%g00:-1<:\p01
 ,:^ >0g10g--*!3g,:#^_$\55+

Try it online!
Explanation
Given the stage number, n, we start by calculating the following three parameters of the pattern:
jump_count = 2 ^ (n - 1)
jump_len   = (n - 1) * 2
width      = (jump_len * jump_count) + 1

The jump_len is normalised to avoid it being zero for a stage 1 kangaroo with:
jump_len += !jumplen

We can then output the jump pattern by iterating over the x and y coordinates of the output area, and calculating the appropriate charater to output for each location. The y coordinate counts down from n - 1 to 0, and the x coordinate counts down from width - 1 to 0. We determine whether a dot needs to be shown with the following formula:
jump_off = x % jump_len
show_dot = (jump_off == y) or (jump_off == (jump_len-y))

The show_dot boolean is used as a table index to determine actual character to output at each location. To save on space, we use the start of the last line of source as that table, which is why our o character ends up being a ,.

J, 28 25 bytes
' o'{~]_&(](|.,}.)"1)=@i.

Saved 3 bytes thanks to @Conor O'Brien.
This is based on the palindrome trick from @muddyfish's solution.
Try it online!
Explanation
' o'{~]_&(](|.,}.)"1)=@i.  Input: integer n
                       i.  Form the range [0, 1, ..., n-1]
                     =@    Equality table with itself.
                           Creates an identity matrix of order n
      ]                    Get n
       _&(          )      Repeat n times on x = identity matrix
           (     )"1         For each row
            |.                 Make a reversed copy
               }.              Get a copy with the head removed
              ,                Append them
          ]                  Use that as the new value of x
' o'{~                     Index into the char array

An alternate approach for 31 bytes: ' o'{~3 :'(}."1,.~|."1)^:y=i.y'. I wish I could find a way to remove that explicit verb... Darn ^:.

@ConorO'Brien Thanks, that does help, I think it will be shorter if tacit

@ConorO'Brien I made it tacit, it is indeed shorter!

Awesome! This is pretty awesome. I keep forgetting the dyadic usage of u&v--quite nice.

C#, 180, 173 171 bytes
Wont win this, posting  for other C# contestants as something they can beat.
n=>{var s=new string[n];for(int a=-1,j=0,i,m=n-1,x=m;j<=m*(Math.Pow(2,n)*n+1);){i=j++%n;s[i]+=x==i?"o":"_";if(i==m&n>1){x+=a;a*=x%m==0?-1:1;}}return string.Join("\n",s);};

complete program:
using System;
public class P
{
    public static void Main()
    {
        Func<int, string> _ = n =>
        {
            var s = new string[n];
            for (int a = -1, j = 0, i, m = n - 1, x = m; j <= m * (Math.Pow(2, n) * n + 1);)
            {
                i = j++ % n;
                s[i] += x == i ? "o" : "_";
                if (i == m & n > 1)
                {
                    x += a;
                    a *= x % m == 0 ? -1 : 1;
                }
            }
            return string.Join("\n", s);
        };

        Console.Write(_(4));
        Console.ReadKey();
    }
}

edit: -7 bytes thanks to @KevinCruijssen
edit: -2 bytes, simplified if

+1 Some things to golf: The ints can be placed inside the for-loop, and you can also add ,i; you can reuse i instead of n-1 after the if-check; || can be |; j++ can be removed and ++ can be added to j. So in total: (n)=>{var s=new string[n];for(int x=0,a=1,j=0,i;j<=Math.Pow(2,n)*(n*n-n);){i=j++%n;s[n-i-1]+=x%n==i?'o':' ';if(i==n-1){x+=a;a*=x==i|x==0?-1:1;}}return string.Join("\n",s);}; (173 bytes)

@KevinCruijssen Nice catch! I'll update once i'm back from work.

@KevinCruijssen I allready golfed out the || and && but kept then in the complete program.

Pyke, 11 bytes
XFd*\o+Q^Vs

Try it here!
 F          -  for i in range(input)
  d*\o+     -     " "*i+"o"
       Q^   -    ^.lpad(input)
         Vs -   repeat len(^): palindromise()
X           - print(reversed(^))

Haskell, 100 bytes
k 1="o"
k n|n<-n-1,m<-n*2=unlines[[last$' ':['o'|mod c m`elem`[m-r,r]]|c<-[0..m*2^n]]|r<-[n,n-1..0]]

Try it online! Usage: k 3.
Explanation:
Given a row r, a column c and m = 2(n-1) an o is set if c mod m equals r or m-r. The outermost list comprehension sets the range of r from n-1 to 0, the next one sets the range of c from 0 to m*2^(n-1) and the innermost acts as conditional returning 'o' if the above formula is fulfilled and ' ' otherwise. This yields a list of strings which is turned into a single newline separated string by unlines. For n=1 the function produces a division-by-zero error, so this case is handled explicitly in the first line.

I really like the ['o'|mod c m\elem`[m-r,r]]` part!

MATL, 27 bytes
XyPt3LZ)2&Pht4LZ)lGqX"h48*c

Try it out at MATL Online

J, 58 47 bytes
' o'{&:>~[:(,.}."1)&.>/(2^<:)#<@(|.,.}."1)@=@i.

Saved 11 bytes using the identity matrix idea from @flawr's solution.
Try it online!
A straightforward application of the definition.
Explanation
For n = 3, creates the identity matrix of order n.
1 0 0
0 1 0
0 0 1

Then mirror it to make
0 0 1 0 0
0 1 0 1 0
1 0 0 0 1

Repeat that 2n-1 times and drop the head of each row on the duplicates
0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1

Use those values as indices into the char array [' ', 'o'] to output a 2d char array
  o   o   o   o
 o o o o o o o o
o   o   o   o   o

Python 2, 115 113 108 98 bytes
lambda n:'\n'.join(map(''.join,zip(*[' '*abs(i)+'o'+~-n*' 'for i in range(-n+1,n-1)*2**~-n])))+'o'

Try it online!
Using range(-n+1,n-1) to create the absolute number of spaces between the bottom  and the o to generate
  o
 o
o
 o

and then appending more copies, rotating 90º everything and appending the last o at bottom right

Pyth, 30 bytes
jC.<V*]+*dtQNh*tQ^2Q*+JUQtP_J^

A program that takes input of an integer and prints the result. Uses a quote mark " instead of o.
Try it online!
How it works
jC.<V*]+*dtQNh*tQ^2Q*+JUQtP_J^    Program. Input: Q
jC.<V*]+*dtQNh*tQ^2Q*+JUQtP_J^QQ  Implicit input fill
      ]                           Yield a one-element list, A
        *dtQ                      cotaining Q-1 spaces
       +    N                     appended with a quote mark.
             h*tQ^2Q              Yield 1+(Q-1)*2^Q
     *                            Repeat A that many times, giving B
                       UQ         Yield [0, 1, 2, ..., Q-1]
                      J           (Store that in J)
                     +   tP_J     Append the reverse of J, discarding the first and last
                                  elements
                    *        ^QQ  Repeat the above Q^Q times, giving C
    V                             Vectorised map. For each pair [a,b] from B and C:
  .<                               Cyclically rotate a left by b characters
 C                                Transpose
j                                 Join on newlines
                                  Implicitly print

JavaScript (ES6), 83 bytes

f=
n=>` `.repeat(n).replace(/ /g,"$'o$`-$`o$'-".repeat(1<<n-1)+`
`).replace(/-.?/g,``)
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

Jelly, 11 bytes
ŒḄ¡ḶUz1Ṛa⁶Y

TryItOnline!
How?
The printable character used is 0.
Builds upon the method of Dennis's answer to his previous question on the subject of kangaroos.
ŒḄ¡ḶUz1Ṛa⁶Y - Main link: n                      e.g. 3
ŒḄ          - bounce, initial implicit range(n) e.g. [1,2,3,2,1]
  ¡         - repeat n times                    e.g. [1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1]
                  i.e. [1,2,3,2,1] bounced to [1,2,3,2,1,2,3,2,1] bounced to [1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1]
   Ḷ        - lowered range (vectorises)        e.g. [[0],[0,1],[0,1,2],[0,1],[0],[0,1],[0,1,2],[0,1],[0],[0,1],[0,1,2],[0,1],[0],[0,1],[0,1,2],[0,1],[0]]
    U       - upend (vectorises)                e.g. [[0],[1,0],[2,1,0],[1,0],[0],[1,0],[2,1,0],[1,0],[0],[1,0],[2,1,0],[1,0],[0],[1,0],[2,1,0],[1,0],[0]]
     z1     - transpose with filler 1
       Ṛ    - ...and reverse                    e.g. [[1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1],
                                                      [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
                                                      [0,1,2,1,0,1,2,1,0,1,2,1,0,1,2,1,0]]
        a⁶  - logical and with space character (all non-zeros become spaces)
          Y - join with line feeds              e.g.    0   0   0   0
                                                       0 0 0 0 0 0 0 0
                                                      0   0   0   0   0

Nice. This ties with my reference solution, ŒḄ¡Ṭ€z0o⁶ṚY.

05AB1E, 16 bytes
L<¹Fû}ð×'o«.BøR»

Try it online!
Why and how?
                 # Example input of n=2.
L<               # [0,1] (Push [1..a], decrement).
  ¹Fû}           # [0,1,0,1,0] (Palindromize n times).
      ð×'o«      # ['o',' o','o',' o','o'] (Push n spaces, append o's).
           .Bø   # ['o ',' o','o ',' o','o '] (Pad with spaces into 2D array, transpose).
              R» # Reverse, join and print.

Perl 6, 104 93 88 bytes
->\n{my @a;@a[$_;$++]="o" for [...] |(n-1,0,n-1)xx 2**n/2;say .join for @a».&{$_//" "}}

Inserts o's into a 2D array, and then prints it.

Python 3, 177 bytes
n=5;f=n-1;w=''
for i in range(n):
 s='';a=0;d='\n'
 if i==f:w='';a=-1;d=''
 for _ in range(2**f):
  s+=' '*(f-i)+'o'+' '*(2*i-1)+w+' '*(n-i-2+a)
 print(s,end=d);w='o'
print('o')

Try it online!

Java 8, 254 bytes
Golfed:
n->{if(n==1)return"o";int k,x,y,m=n+n-2;char[][]p=new char[n][m];for(y=0;y<n;++y)for(x=0;x<m;)p[y][x++]=' ';for(k=0;k<m;++k)p[k<n?n-k-1:k-n+1][k]='o';String s="";for(y=0;y<n;++y){for(k=0;k<1<<(n-1);++k)for(x=0;x<m;)s+=p[y][x++];if(y==n-1)s+='o';s+='\n';}

Ungolfed:
import java.util.function.*;

public class LeapingKangaroos {

  public static void main(final String[] args) {
    for (int i = 1; i <= 4; ++i) {
      System.out.println(toString(n -> {
        if (n == 1) {
          return "o";
        }
        int k, x, y, m = (n + n) - 2;
        char[][] p = new char[n][m];
        for (y = 0; y < n; ++y) {
          for (x = 0; x < m;) {
            p[y][x++] = ' ';
          }
        }
        for (k = 0; k < m; ++k) {
          p[k < n ? n - k - 1 : (k - n) + 1][k] = 'o';
        }
        String s = "";
        for (y = 0; y < n; ++y) {
          for (k = 0; k < (1 << (n - 1)); ++k) {
            for (x = 0; x < m;) {
              s += p[y][x++];
            }
          }
          if (y == (n - 1)) {
            s += 'o';
          }
          s += '\n';
        }
        return s;
      } , i));
      System.out.println();
      System.out.println();
    }
  }

  private static String toString(final IntFunction<String> func, final int level) {
    return func.apply(level);
  }

}

Program output:
o

 o o
o o o

  o   o   o   o
 o o o o o o o o
o   o   o   o   o

   o     o     o     o     o     o     o     o
  o o   o o   o o   o o   o o   o o   o o   o o
 o   o o   o o   o o   o o   o o   o o   o o   o
o     o     o     o     o     o     o     o     o

PHP, 157 bytes
for($i=$n=$argv[1],$r=str_repeat;$i>0;)echo$r($r(' ',$i-1).'o'.$r(' ',2*$n-2*$i-1).($i==$n|$i==1?'':'o').$r(' ',$i-2),2**($n-1)).($i--==1&$n!=1?'o':'')."\n";

Ungolfed:
for($i=$n=$argv[1];$i>0;) {

    // Spacing from beginning of pattern to first 'o'
    $o  = str_repeat(' ',$i-1);

    // First 'o' for the ascent
    $o .= 'o';

    // Spacing between ascent and descent
    $o .= str_repeat(' ',2*$n-2*$i-1);

    // Second 'o' for the descent, unless we are at the apex or the bottom
    $o .= ($i==$n|$i==1?'':'o');

    // Spacing to the end of the pattern
    $o .= str_repeat(' ',$i-2);

    // Repeat the pattern 2^(n-1) times
    echo str_repeat($o, 2**($n-1));

    // Output final 'o' if we are at the bottom in the last pattern
    echo $i--==1&$n!=1?'o':'';

    // End of line
    echo "\n";

}

You can replace every 'o' with 1 and every '' with 0. Hope that works, Also, the spaces can be replaced by O or 9. The important is the pattern, according to the rules. But verify first

Canvas, 6 bytes
o×／Ｌ［│

Try it here!
Explanation
o×/L[|
o×     repeat o input times
  /    make an antidiagonal using it
   L   get width without popping
    [| palindromize width times


text:
Approximate Brun's Constant
Brun's constant is the value to which the sum of the reciprocals of twin prime pairs (1/p and 1/(p+2) where p and p+2 are both prime) converges. It is approximately 1.902160583104.
Given a positive integer N, approximate Brun's constant by summing the reciprocals of the twin prime pairs where both primes in the pair are less than N, and output the approximation.
Rules

N will be a positive integer within the representable range for your language.
The output must be as accurate as possible to the true value, within the limits of your language's floating-point implementation, ignoring any potential issues due to floating-point arithmetic inaccuracies. If your language is capable of arbitrary-precision arithmetic, it must be at least as precise as IEEE 754 double-precision arithmetic.
Alternatively, an exact fraction may be output in any consistent, unambiguous format.
If a prime appears in multiple twin prime pairs (e.g. 5, part of both (3, 5) and (5, 7)), its reciprocal contributes to the sum each time.

Test Cases
2 -> 0
6 -> 0.5333333333333333
10 -> 0.8761904761904762
13 -> 0.8761904761904762
100 -> 1.3309903657190867
620 -> 1.4999706034568274
100000 -> 1.67279958482774

Can an exact fraction be output?

@LegionMammal978 Yes, I'll clarify.

Side note: the value 1.902160583104... for Brun's constant is only conjectured; not even the first significant figure has been rigorously computed (that is, it's not even known whether it's greater than or less than 2).

@GregMartin While that's true, it's also the best approximation we currently have.

5 is the only prime that appears in two prime pairs

@ChristianSievers My number theory is a bit rusty in places, so I opted for safe rather than sorry. :)

He's right though. All primes larger than 3 must be coprime with 6, so they're congruent to 1 or -1 modulo 6. If p, p+2, and p+4 are all prime, one of them is congruent to 3 modulo 6, which is only possible if one of them (p, to be precise) is equal to 3.

Python 3, 78 77 75 70 68 62 bytes
f=lambda n,k=3,m=1,j=0:k<n and-m%k*j*2/k+f(n,k+2,m*k**4,m%k/k)

Thanks to @xnor for golfing off 2 4 bytes and paving the way for 4 more!
Try it online!
Background
Recall that Wilson's theorem states that for all integers k > 1,

where a ≡ b (mod d) means that a - b is evenly divisible by d, i.e., a and b have the same residue when divided by d.
In Wilson Theorems for Double-, Hyper-, Sub- and Super-factorials, the authors prove generalizations for double factorials, on which this answer builds. The double factorial of an integer k ≥ 0 is defined by

Theorem 4 of the aforementioned paper states the following.

Elevating both sides of the congruences to the fourth power, we deduce that

for all odd primes p. Since 1!! = 1, the equivalence holds also for p = 2.
Now, doing the same to Wilson's theorem reveals that

Since

it follows that

whenever p is prime.
Now, let k be an odd, positive, composite integer. By definition, there exist integers a, b > 1 such that k = ab.
Since k is odd, so are a and b. Thus, both occur in the sequence 1, 3, …, k - 2 and

where | indicates divisibility.
Summing up, for all odd integers k > 1

where p(k) = 1 if k is prime and p(k) = 0 if k is composite.
How it works
When the function f is called with a single argument, k, m, and j are initialized as 3, 1, and 0.
Note that ((k - 2)!!)4 = 1!!4 = 1 = m. In fact, the equality m = ((k - 2)!!)4 will hold at all times. j is a float and will always be equal to ((k - 4)!!)4 % (k - 2) / (k - 2).
While \$k < n\$, the right argument of and will get evaluated. Since \$j = \frac{\mod(\left(\left(k - 4\right)!!\right)^4 , k - 2)}{k - 2}\$, as proven in the first paragraph, \$j = \frac{1}{k - 2}\$ if \$k - 2\$ is prime and \$j = 0\$ if not. Likewise, since \$\mod(m,k) = \left(\left(k - 2\right)!!\right)^4\$ equals \$1\$ if \$k\$ is prime and \$0\$ if not, \$\mod(-m,k) = k - 1\$ if \$k\$ is prime and \$\mod(-m , k) = 0\$ if not. Therefore, -m%k*j*2/k evaluates to \$\frac{2\left(k - 1\right)}{k\left(k - 2\right)} = \frac{\left(k - 2\right) + k}{k(k - 2)} = \frac{1}{k} + \frac{1}{k - 2}\$ if the pair \$\left(k - 2, k\right)\$ consists of twin primes and to \$0\$ if not.
After computing the above, we add the result to the return value of the recursive call f(n,k+2,m*k**4,m%k/k). \$k\$ gets incremented by \$2\$ so it only takes odd values‡†, we multiply \$m\$ by \$k^4\$ since \$mk^4 = \left(\left(k - 2\right)!!\right)^4k^4 = \left(k!!\right)^4\$, and pass the current value of \$\frac{\mod(m,k)}{k}\$ – which equals \$\frac{1}{k}\$ if the "old" \$k\$ is a prime and \$0\$ if not – as parameter \$j\$ to the function call.
Finally, once \$k\$ is equal to or greater than \$n\$, \$f\$ will return False and the recursion stops. The return value of \$f(n)\$ will be the sum of all \$\frac{1}{k} + \frac{1}{k - 2}\$ such \$\left(k - 2, k\right)\$ is a twin prime pair and \$k < n\$, as desired.

‡ The results from the Background paragraph hold only for odd integers. Since even integers cannot be twin primes, we can skip them safely.

I think your expression is the same as m%k*(j/k+j/(k-2)).

Yes, that works. Thanks!

Another save

Nice observation that ((k-2)!!)^4 = p(k) modulo p for odd p. I haven't worked through your argument, but here's one I came up with (that might be the same in essence). Work modulo p in the set {1,2,..,p-1}, the evens are exactly the negatives of the odds. So, prod(odds) = ± prod(evens). Wilson's Theorem tells us that prod(all) = - p(k). Since prod(all) = prod(odds) * prod(evens) = prod(odds) * ± prod(evens), we have  prod(odds)^2 = ±p(k) and so prod(odds)^4 = p(k)^2 = p(k).

Nice! I tried expressing the sum as a single fraction, but computing part of it in j hadn't occurred to me. Thanks again! Your proof is a lot simpler than the one from the paper.

Jelly, 15 14 bytes
’ÆRµ_2fµ+2;µİS

Try it online!
How it works
’ÆRµ_2fµ+2;µİS  Main link. Argument: n

’               Decrement; yield n-1.
 ÆR             Prime range; yield all primes in [1, ..., n-1].
   µ            New chain. Argument: r (prime range)
    _2          Subtract 2 from all primes.
      f         Filter; keep all p-2 that appear in r.
       µ        New chain. Argument: t (filtered range)
        +2      Add 2 to all primes in s.
          ;     Concatenate with s.
           µ    New chain. Argument: t (twin primes)
            İ   Take the inverses.
             S  Sum.

Jelly, 16 14 bytes (with a little help from @Dennis)
’ÆRṡ2_/2+$$ÐḟFİS

Try it online!
While trying to improve my previous answer, I thought up a totally different algorithm, and it comes in somewhat shorter. I'm using a different post for it, as is the standard here for an answer that uses a different technique.
Dennis suggesting replacing _/2+$$Ðḟ with Iċ¥Ðf2; I'd completely forgotten about the possibility of a dyadic filter. As such, this algorithm now ties with the one that Dennis' answer used.
Explanation
’ÆRṡ2Iċ¥Ðf2FİS
’                  Decrement.
 ÆR                Primes from 2 to the argument inclusive
                   (i.e. 2 to the original input exclusive).
   ṡ2              Take overlapping slices of size 2.
        Ðf         Keep only elements where the following is true:
       ¥           {the second parse of, which parses like this}
     Iċ   2          the differences (I) contain (ċ) 2
           F       Flatten.
            İ      Take 1/x {for every list element}.
             S     Sum.

2_/2+$$Ðḟ can become Iċ¥Ðf2.

Brachylog, 17 bytes
{>I-₂:I{ṗ/₁}ᵐ}ᶠc+

Try it online!
This is the brand new version of Brachylog, with a shiny code page!
Explanation
{            }ᶠ        Find all valid outputs of the predicate in brackets
               c+      Output is the sum of that list after flattening it

 >I                    Input > I
   -₂:I                The list [I-2, I]
       {   }ᵐ          Map:
        ṗ/₁              Must be prime and the output is its inverse

05AB1E, 19 14 bytes (-5 @Emigna)
<LDpÏÍDpÏDÌ«zO

Try it online!

<LDpÏÍDpÏDÌ«zO to save 5 bytes.

MATL, 16 bytes
liqZqtd2=)t2+h/s

Try it online!
Consider input 13 as an example.
l     % Push 1
      %   STACK: 1
i     % Input N
      %   STACK: 1, 13
q     % Subtract 1
      %   STACK: 1, 12
Zq    % Primes up to that
      %   STACK: 1, [2 3 5 7 11]
t     % Duplicate
      %   STACK: 1, [2 3 5 7 11], [2 3 5 7 11]
d     % Consecutive differences
      %   STACK: 1, [2 3 5 7 11], [1 2 2 4]
2=    % Compare with 2, element-wise
      %   STACK: 1, [2 3 5 7 11], [0 1 1 0]
)     % Use as logical index to select elements from array
      %   STACK: 1, [3 5]
t     % Duplicate
      %   STACK: 1, [3 5], [3 5]
2+    % Add 2, element-wise
      %   STACK: 1, [3 5], [5 7]
h     % Concatenate horizontally
      %   STACK: 1, [3 5 5 7]
/     % Divide, element-wise
      %   STACK: [0.3333 0.2 0.2 0.1429]
s     % Sum of array. Implicitly display
      %   STACK: 0.8762

Mathematica, 48 47 bytes
Thanks to JungHwan Min for saving 1 byte!
If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0]~Sum~{i,#-1}&

Unnamed function taking a positive integer as input and returning an exact fraction; for example, If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0]~Sum~{i,#-1}&[10] returns 92/105.
If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0] tests whether both i and i-2 are prime, returning the sum of their reciprocals if so and 0 if not. ~Sum~{i,#-1}& then returns the sum of those contributions for all values of i less than the input.
Previous submission:
If[And@@PrimeQ@{i,g=i-2},1/i+1/g,0]~Sum~{i,#-1}&

Now that's just spooky. I give up. ⚐

I wondered if "exact fraction" meant Mathematica :)

-1 byte: If[PrimeQ/@(i&&(g=i-2)),1/i+1/g,0]~Sum~{i,#-1}&

One can get an arbitrary-precision number by adding two bytes, N@, in front of the code.

Nice golfing of the condition! It's true that N returns a decimal approximation to a real number; however, it requires extra bytes to display more than 6 sig figs or so, and no matter how many sig figs are displayed, it's still less accurate than the fraction itself.

JavaScript (ES6), 67 66 bytes
Saved 1 byte thanks to @Arnauld
f=n=>--n>1&&((p=x=>n%--x?p(x):x==1)(n)&&p(n-=2)&&1/n+++1/++n)+f(n)

Outputs false for test case 2, which is allowed by default.
Test snippet

f=n=>--n>1&&((p=x=>n%--x?p(x):x==1)(n)&&p(n-=2)&&1/n+++1/++n)+f(n)

g=n=>console.log("Input:",n,"Output:",f(n))

g(2)
g(6)
g(10)
g(13)
g(100)
g(620)

I think 1/n+++1/++n saves a byte.

@Arnauld Thanks. For some reason I didn't know that +++ doesn't always throw an error...

Octave, 45 bytes
@(n)sum(all(isprime(m=[h=3:n-1;h-2]))*m'.^-1)

Explanation:
m=[h=3:n-1;h-2]             generate an concatenate two ranges 3:n-1 and 1:n-3
rec=m'.^-1                  transpose and reciprocal
idx=all(isprime(m))         create a logical [0 1 ..] array  if both ranges are prime set 1 else set 0
sum1 = idx * rec            matrix multiplication(extrat elements with logical index and sum along the first dimension)
sum(sum1)                   sum along the second dimension

Try It Online!

Perl 6, 59 51 bytes
{sum 1 «/»grep((*-(2&0)).is-prime,^$_).flatmap:{$_-2,$_}}
{sum 1 «/»grep(*.all.is-prime,(-2..*Z ^$_)).flat}

-2..* Z ^$_ zips the infinite list -2, -1, 0, 1, ... with the list 0, 1, ... $_-1 ($_ being the argument to the function), producing the list (-2, 0), (-1, 1), (0, 2), ..., ($_-3, $_-1).  (Obviously none of these numbers less than 3 can be in a prime pair, but 3..* Z 5..^$_ is a few bytes longer, and none of the extra numbers are prime.)
The grep selects only those pairs where all (that is, both) numbers are prime, and the flat flattens them into a plain list of numbers.
«/» is the division hyperoperator; with the list on the right and 1 on the left, it turns the list of prime pairs into their reciprocals, which is then summed by sum.

Clojure, 147 bytes
(fn[n](let[p #(if(> % 2)(<(.indexOf(for[a(range 2 %)](mod % a))0)0))](reduce +(for[a(range 2 n)](if(and(p a)(p(- a 2)))(+(/ 1 a)(/ 1(- a 2)))0)))))

And Clojure comes dead last, as usual.
Ungolfed:
; Returns the primality of a number.
(defn prime? [n]
  (if (> n 2)
    (< (.indexOf (for [a (range 2 n)] (mod n a)) 0) 0)))

; Calculates the actual Brun's Constant. ' (Stupid highlighter)
(defn brunsconst [n]
  ; Adds all of the entries together
  (reduce
    +
    ; For a in range(2, n):
    (for [a (range 2 n)]
      (let [b (- a 2)]
        ; If both a and a-2 are prime:
        (if (and (prime? a) (prime? b))
          ; Place (1/a + 1/a-2) on the array, else 0
          (+ (/ 1 a) (/ 1 b)) 0)))))

Jelly, 19 bytes
’ÆRḊµ_Æp=2Tịµ_2;µİS

Try it online!
I have a feeling that this is improvable, but I can't immediately see how.
Explanation
’ÆRḊµ_Æp=2Tịµ_2;µİS
 ÆR                  Generate all primes from 2 to n inclusive
’                    Subtract 1
   Ḋ                 Remove first element
’ÆRḊ                 Generate all primes from 3 to n-1 exclusive

     _Æp             Subtract the previous prime (i.e. calculate the prime gap)
        =2           Compare to 2
          Tị         Take elements of the input where the comparison is true
     _Æp=2Tị         Filter a list of primes to the latter halves of prime pairs

             _2      Subtract 2
               ;     Append
             _2;     Append the list to the list with 2 subtracted from it
                 İ   Take reciprocals
                  S  Sum
                 İS  Take the sum of the reciprocals

The µ connect all these portions together pipeline-style, with each taking the output of the one before as its input.

Pyth - 22 21 17 bytes
I think that refactoring will help.
scL1sf.APM_MTm,tt

Test Suite.

Julia 0.4, 48 46 bytes
!n=sum(1./[(p=n-1|>primes)∩(p-2);p∩(p+2)])

Try it online!

APL NARS, 216 bytes, 108 chars
  r←z n;h;i;k;v
  i←0⋄n-←1⋄h←1+⍳n-1⋄→B
A:k←i⊃h⋄h←k∪(0≠k∣h)/h
B:→A×⍳(⍴h)≥i+←1
  r←+/÷(v-2),v←(h=1⌽h+2)/h

this would use the "Crivello di Eratostene" for find the sublist in 1..arg of request primes. Test:
  z¨2 6 10 13 100 620
0 0.5333333333 0.8761904762 0.8761904762 1.330990366 1.499970603
  z 100000
1.672799585

Husk, 14 bytes
ṁ\Σfo=2F-Ẋefṗŀ

Try it online!
Explanation
ṁ\Σfo=2F-Ẋefṗŀ
             ŀ   lowered range, 0..n-1
           fṗ    filter primes
         Ẋe      get each consecutive pair
   f   F-        filter where difference
    o=2          equals 2
  Σ              concat, list of pairs to flattened list
ṁ\               map 1/n and then sum

Pari/GP, 50 bytes
n->forprime(p=s=0.,n,isprime(q=p-2)&&s+=1/p+1/q);s

Try it online!

Vyxal sḋ, 13 12 bytes
~æ2l'÷ε2=;fĖ

Try it online or verify all test cases.
Explanation:
~             # Filter the range 0 to n-1 by:
 æ            #   Is prime
  2l          # Get the overlapping groups of 2
    '    ;    # Filter those by:
     ÷ε       #   Absolute difference of the list
       2=     #   Equals 2
          f   # Flatten to make one list
           Ė  # Take the reciprocal of each
              # Sum with the s flag
              # Convert to decimal format with the ḋ flag

Bash + GNU utilities, 86 85 bytes
for((k=4;k<$1;k++,j=k-2)){ [ `factor $k $j|wc -w` = 4 ]&&x=$x+1/$k+1/$j;};bc -l<<<0$x

Try it online!
Constructs a large arithmetic expression and then feeds it to bc -l to evaluate it.
Edit: Mistakenly left in a $(...) pair from an old version with nested command substitution; changed to backticks to save a byte.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Permanently self-modifying code
Now, we all know most languages have very simple ways to "self-modify" code.
However, what if you were to actually modify the code and edit parts of it...on disk?
Your goal is to make code that prints a number, then edits its own file to replace the number with the next one in the Fibonacci sequence like so:
$ ./program
1
$ ./program
1
$ ./program
2
$ ./program
3
$ ./program
5
[etc...]

Rules

You may not store the number(s) "outside" of the code. No comments, no telling the script to exit, no EOF, etc.
If your code works with any filename, subtract 2 from your byte amount and write $BYTESNOW ($ORIGINALBYTES - 2) in your title. (Filenames are assumed to be within the range of any alphanumeric file path.)
Your code must write the output to the file on it's own, without any external piping assistance.
Your code can start from one or zero. It doesn't matter.

Next time, please post your idea in the Sandbox instead and leave the post there for a few days to receive feedback.

Is it allowed to call the program by invoking the interpreter of the programming language (e.g. perl6 program), or does it have to include the shebang line so that it can be called as ./program?

Also, if we don't want to go for the -2 bytes bonus, can we choose a single-byte filename or does it have to be program, and can we assume it's located in the current working directory?

Can it be allowed to fail when large numbers begin implicitly converting to exponential notation?

Why only 2 bytes bonus? Most languages, Eg. Lua, have it easier just to do "a" instead of arg[0]. It doesn't seem worth it.

@ATaco I just used the bonus even though not using it would be shorter. It seems less "cheaty" that way, because you're not assuming anything.

Bash, 52 47 (49-2) bytes
EDITS:

Saved 5 bytes, by starting with 1 instead of 0. Thanks @Leo !

Golfed
A=$[1+0]
echo $A
sed -ri "s/\w+\+(\w+)/\1+$A/" $0

Test
>for i in `seq 10`
> do
> ./fibo
> done
1
1
2
3
5
8
13
21
34
55

I think you could save 1 byte by starting from [1+0] instead of [-1+1] (see 4th rule of the challenge)

Actually, that would make you save even more bytes by removing the -? from the regex. And since you're there, you could also remove the first capturing group :)

@Leo That's a nice advice, thank you !

Batch, 81 bytes
@call:c
@set/az=x+y
@echo %x%
@echo>>%0 @set/ax=%z%,y=%x%
:c
@set/ax=0,y=1

Note: the trailing newline is significant. Requires the script to be invoked using its full name including extension. Output starts at 0.
Since Batch can't realistically edit a file, I just add extra lines to the end of the file, so eventually it will know which the next number to print is. The >>%0 placement saves a byte because I can't precede it with a digit.

-14 bytes, without forcing filename

@HackingAddict1337 Ah, I don't remember that bonus.

Also, my batch file now measures 79 bytes for some reason?

I don't want to put my name to your weird @goto& behaviour, or even your use of an uninitialised variable, so feel free to post your solution as an answer.

all right then (goto& == cmd/c)

Python 3.6, 96 91 (93-2) bytes
a,b=0,1
f=open(__file__,"r+");next(f);f.write(f"a,b={b,a+b}\n{next(f)}{f.seek(0)}");print(b)

hardcoding the filename would save 5 bytes (88 bytes):
a,b=0,1
f=open("f","r+");next(f);f.write(f"a,b={b,a+b}\n{next(f)}{f.seek(0)}");print(b)

Saved some bytes thanks to @Artyer

How about this (88 bytes) a,b=0,1
f=open('f','r+');next(f);f.write(f'a,b={b,a+b}\n{next(f)}{f.seek(0)}');print(b)#

Python 2, 118 111 bytes ( 113 - 2 )
a,b=0,1;print a
f=open(__file__,'r+')
s=f.read()
s=s.replace(s[4:s.find(';')],`b`+','+`a+b`)
f.seek(0)
f.write(s)

It works with any valid filename. There is not much to explain here, the code itself is very verbose.
Thanks to FlipTack for reminding me, close() is not mandatory.

Can't you just use f=open(...) instead of the with statement?

Node.js, 152 137 bytes (139 - 2)
Separated with newlines for clarity, not part of byte count.
f=_=>require('fs').writeFileSync(__filename,
`f=${f};f()`.replace(/(\d[^,]*),(\d[^\)]*)/,
(m,a,b)=>`${b=+b},${+a+b}`),console.log((0,1)));
f()

Explanation:
f=_=>                          // define `f` as function with a single unused argument `_`
  require('fs').writeFileSync( // import the standard filesystem module and overwrite file
    __filename,                // string var containing path of file for current module
    `f=${f};f()`.replace(      // template string containing source of entire script
      /(\d[^,]*),(\d[^\)]*)/,  // regexp to match and group the numbers in this script
      (m,a,b)=>                // replace function with arguments match, group a, group b
        `${b=+b},${+a+b}`      // template string incrementing fibonacci numbers in place
    ),                         // end replace()
    console.log(               // prints to stdout, `undefined` passed to argument
      (0,1)                    // comma separated group returns value of last expression
    )                          // end console.log()
  )                            // end fs.writeFileSync()
;                              // end statement defining `f` as arrow function
f()                            // run function to modify script and print fibonacci number

Usage:
// assuming above script is stored in program.js
$ node program
1
$ node program
1
$ node program
2
$ node program
3
$ node program
5
...

bash + Unix utilities, 43 bytes (45-2)
dc -e9k5v1+2/z^5v/.5+0k1/p;sed -i s/z/z1+/ $0

The first time this is run, it uses dc to compute the 1st Fibonacci number via the Binet formula. Each call to sed modifies the program by changing the string passed to dc; this change tells dc to add an additional 1 to the exponent in the formula, which causes it to compute the next number in the Fibonacci sequence each time.
Test
> for k in {1..10}
> do
> ./fib
> done
1
1
2
3
5
8
13
21
34
55

To illustrate how it works, at this point, after the 55 is printed, the program has been modified to read:
dc -e9k5v1+2/z1+1+1+1+1+1+1+1+1+1+^5v/.5+0k1/p;sed -i s/z/z1+/ $0

so running it again yields
> ./fib
89

and the program now reads:
dc -e9k5v1+2/z1+1+1+1+1+1+1+1+1+1+1+^5v/.5+0k1/p;sed -i s/z/z1+/ $0

I like this ! Well done !

@zeppelin Thank you -- this avoids the issues with the previous version we had.

C, 142 bytes (144 - 2)
void main(int x,char**a){FILE*f=fopen(*a,"r+");fseek(f,27,0);char n=fgetc(f),m=fgetc(f);fseek(f,27,0);printf("%d\n",fputc(fputc(m,f)?n+m:1,f));}

It's pretty straight forward. First it reads then saves the two chars at position 0x1A in the header. I probably could've looked deeper to find a safer spot to save the data but it works for me on my machine running OSX, compiled with GCC 4.2ish and I doubt it's very portable. Also, since it's based off chars it overflows after the 13th iteration.
It gives the output:
1
1
2
3
5
8
13
21
34
55

SmileBASIC 3, 99 bytes (101 -2)
-2 byte bonus because it works with any filename.
A=0B=1F$="TXT:"+PRGNAME$()S$=LOAD(F$)SAVE F$,SUBST$(S$,0,INSTR(S$,"F"),FORMAT$("A=%DB=%D",B,A+B))?A+B

This one does work, and it somehow ended up being the same size as my broken one!

It's much shorter if you don't do the bonus

forcing a specific filename makes me feel like a freak. I'm beating half these answers anyway

I think not turning off the LOAD dialog is much worse.

It's actually shorter if you load it into slot 1 and use PRGEDIT commands to replace the first line (and add a linebreak after A=0B=1)
And you also don't need A=0 the first time.

Dang, I saw this one and immediately thought "SmileBASIC". I probably couldn't come close anyways. Nicely done!
Btw I'm known as Mr_Mo on sbs

Batch, 66 - 2 = 64 bytes
Uses \r line terminators (not traditional \r\n)
@call:a
@set/az=x+y
@(set/p=,x=%z%,y=%x%)<%0>>%0
:a
@goto&set/ax=1

Any filenames are allowed, except for 0-9 (which isn't a .bat anyways)

Credits to:
Original answer by @Neil
@dbenham mentioning the weird behavior of GOTO :invalid_or_empty label (originally discovered by some Russians):

In summary, (GOTO) 2>NUL behaves like EXIT /B, except it allows execution of concatenated commands in the context of the caller!

Warning: will overflow if the number exceeds 2^31-1 (47), because batch integers are 32-bits.

Clojure, 209 204 195 bytes
0 1(let[u #(apply str %)a"./src/s.clj"p #(Long/parseLong(u %))l(fn[v](split-with #(Character/isDigit %)v))c(slurp a)[n[_ & r]](l c)[m r](l r)b(+(p n)(p m))](println b)(spit a(str(p m)" "b(u r))))

-5 bytes by switching to parse the numbers as a long instead of an integer, and removing a couple missed spaces.
-9 bytes by removing the space between the second number and (let...) (most expensive space ever!).
See the pregolfed code comments for a description.
Tested again, and it no longer throws unmatched bracket errors. It works up to 7540113804746346429, at which point it throws an integer overflow exception.
Also note, this assumes the source code is located at "./src/s.clj".
0 1 ; Starting numbers
(let [; The first 4 entires are shortcuts to functions and data that are used more than once
      u #(apply str %) ; Turns a list into a string
      a "./src/s.clj" ; Current location
      p #(Integer/parseInt (u %)) ; Integer parsing shortcut
      ; Used to split a string on digits to parse them out
      l (fn [v] (split-with #(Character/isDigit %) v))
      src (slurp a) ; Get the source
      [n [_ & r]] (l src) ; Use deconstructuring to grab the first number
      [m r] (l r) ; Same as above, grabbing the second number
      n' (+ (p n) (p m)) ; Parse the 2 numbers, and add them
      ; Put everything back together, only this time with the new numbers
      k (str (p m) " " n' (u r))]
  (println n') ; Print the new number
  (spit a k)) ; Overwrite the old source

R, 145 bytes (147 - 2)
a=c(1,1)
cat(a[1])
R=readLines(f<-sub("^.+=","",grep("^--f",commandArgs(F),v=T)))
cat(c(sprintf("a=c(%i,%i)",a[2],sum(a)),R[-1]),file=f,sep="\n")

(Has a trailing newline). It works with any valid filename.

Perl 6, 67 62 bytes (64 - 2)

say (1,1,*+*...*)[1];$*PROGRAM.&{.spurt: .slurp.&{S/\[<(\d+/{$/+1}/}}

say 0+1;$*PROGRAM.&{.spurt: .slurp.&{S/(\d+).(\d+)/$1+{$0+$1}/}}

Ruby, 68 bytes (70-2)
p$a=1+0
f=open$0,'r+'
s=f.read.sub /\d+.(\d+)/,"\\1+#$a"
f.seek 0
f<<s

Stacked, noncompeting, 65 (67 - 2) bytes
Some issues regarding file IO were fixed in the most recent series of commits. Thus, noncompeting.
2:>
:sum\tail...\stack:0#out repr LF+program LF split last+d0\write

Here's a link to the github.
Example execution
(I omitted the actual path for clarity.)
C:\
λ type permanently-self-modifying-code.stk
2:>
:sum\last\stack:0#out repr LF+program LF split last+d0\write
C:\
λ stacked permanently-self-modifying-code.stk
1

C:\
λ stacked permanently-self-modifying-code.stk
1

C:\
λ stacked permanently-self-modifying-code.stk
2

C:\
λ stacked permanently-self-modifying-code.stk
3

C:\
λ stacked permanently-self-modifying-code.stk
5

C:\
λ stacked permanently-self-modifying-code.stk
8

Explanation
How this works is by taking a pair of numbers to begin the sequence (2:> in this case is the integer range [0, 2), which is (0 1)), then performing the Fibonacci transformation on them, like so:
:sum\last\                     top of stack: (x y)
:              duplicate.             stack: ((x y) (x y))
 sum           sum of TOs.            stack: ((x y) x+y)
    \          swap order.            stack: (x+y (x y))
     last      obtain last element.   stack: (x+y y)
         \     swap order.            stack: (y x+y)

On each run, this transformation is executed on the top of stack. Then, the stack is pushed to the stack, duplicated, and its first member obtained (stack:0#). This item is then outputted, and is the desired Fibonacci number. repr then takes the representation of the stack and appends a newline. Then, the program is pushed to the stack, and split on newlines. Then, we take the last member (the last line), and append this to the aforementioned string. Finally, we push d0 (the file itself; think dollar sign 0 == $0.) and write to it.

Python 3.8 (pre-release), 73 bytes
b=c=1;exec(a:="print(b);open(*'aw').write(f'b,c={c,b+c};exec(a:=%r)'%a)")

filename should be a
Explanation
b=c=1;exec(a:="print(b);open(*'aw').write(f'b,c={c,b+c};exec(a:=%r)'%a)")
b=c=1                                                                      # Set b and c to 1
           a:="print(b);open(*'aw').write(f'b,c={c,b+c};exec(a:=%r)'%a)"   # Set a to the string and return it
      exec(                                                             )  # Execute `a` as python code
               print(b)                                                    # Prints b
                        open(*'aw')                                        # Opens a files named `a` in write mode
                                          f'b,c={c,b+c};exec(a:=%r)'%a     # String Formatting: 'b,c=(<c>,<b+c>);exec(a:="<a>")'
                                   .write(                            )    # Write the string to the file

Try it online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Detect if your program has been mutated
Write a program that terminates without an error.
If any single byte is substituted by any other byte the program should output
CORRUPTED

Do not read your source code from a file
Your program should not produce any other output

This is code-golf so the shortest answer in bytes wins.
Edit: removed "NOT CORRUPTED" requirement

[tag:radiation-hardening] has a host of similar questions, but I haven't found any that are quite like this one.

To the downvoters: I suspect this is possible (if very difficult), if you pick the right language. Please don't close or delete the question unless you think there's something wrong with it other than being impossible.

What does changed mean? Substituted by another byte?

@ais523 FWIW I downvoted the challenge because it seems hastily written, not because I think it's too difficult.

@Dennis sandboxed!

Ignoring for a moment that the challenge you sandboxed is substantially different from the challenge you posted here, sandbox or no sandbox makes no difference. I'm sure you could find ways to make the challenge clearer by writing more than three sentences, just as you could have made your comment clearer by writing more than one word.

@Dennis what is unclear?

It's not that anything is unclear, but it could be made clearer. You could clarify if a full program is required, add an example program and illustrate all possible modifications, mention how single-byte substitutions would affect a UTF-8 encoded file, add a script that can be used to test submissions, mention that the program should not take input, etc.

A Pear Tree, 76 bytes
$@='NOT ';print"$@CORRUPTED"__DATA__ =®®”print"$@CORRUPTED"__DATA__ =®®”Ê®›~

This program contains a few stray octets that aren't valid UTF-8. As such, it's shown as it looks in Windows-1252. (By default, if A Pear Tree sees a non-ASCII octet in a string literal or the like it treats it as an opaque object and doesn't try to understand it beyond being aware of what its character code is; this behaviour can be changed via an encoding declaration but the program doesn't have one. So the program is logically in "unspecified ASCII-compatible character set". All the non-ASCII octets are in comments anyway, so it doesn't really matter.)
Explanation
A Pear Tree checksums the program, looking for the longest substring that has a CRC-32 of 00000000. (If there's a tie, it picks the octetbetically first.) Then the program gets rotated to put it at the start. Finally, the program gets interpreted as a language that's almost a superset of Perl, defining a few things that are undefined in Perl to work the same way as in Python (and with a few minor changes, e.g. print prints a final newline in A Pear Tree but not in Perl). This mechanism (and the language as a whole) was designed for polyglot and radiation-hardening problems; this isn't the former, but it's definitely the latter.
In this program, we have two notable substrings that CRC-32 to 00000000; the entire program does, and so does print"$@CORRUPTED"__DATA__ =®® by itself (which appears twice). As such, if the program is uncorrupted, it'll set $@ to NOT  and then print it followed by CORRUPTED. If the program is corrupted, then the CRC-32 of the program as a whole will fail to match, but one of the shorter sections will remain uncorrupted. Whichever one is rotated to the start of the program will just print CORRUPTED, as $@ will be the null string.
Once the string's been printed, __DATA__ is used to prevent the rest of the program running. (It crosses my mind writing this that __END__ could be used instead, which would clearly save two bytes. But I may as well post this version now, because I've spent a bunch of time verifying it, and a modified version would have to be re-verified due to the CRC changes; and I haven't put a huge amount of effort into golfing the "payload" yet, so I want to see if anyone has other improvements in the comments that I can incorporate at the same time. Note that # doesn't work in the situation where a character is corrupted into a newline.)
You might be wondering how I managed to control the CRC-32 of my code in the first place. This is a fairly simple mathematical trick based on the way that CRC-32 is defined: you take the CRC-32 of the code, write it in little-endian order (the reverse of the byte order that's normally used by CRC-32 calculation programs), and XOR with 9D 0A D9 6D. Then you append that to the program, and you'll have a program with a CRC-32 of 0. (As the simplest example possible, the null string has a CRC-32 of 0, thus 9D 0A D9 6D also has a CRC-32 of 0.)
Verification
A Pear Tree can handle most sorts of mutations, but I'm assuming "changed" means "replaced with an arbitrary octet". It's theoretically possible (although unlikely in a program this short) that there could be a hash collision somewhere that lead to the wrong program running, so I had to check via brute force that all possible octet substitutions would leave the program working correctly. Here's the verification script (written in Perl) that I used:
use 5.010;
use IPC::Run qw/run/;
use warnings;
use strict;
undef $/;
$| = 1;
my $program = <>;
for my $x (0 .. (length $program - 1)) {
    for my $a (0 .. 255) {
        print "$x $a    \r";
        my $p = $program;
        substr $p, $x, 1, chr $a;
        $p eq $program and next;
        alarm 4;
        run [$^X, '-M5.010', 'apeartree.pl'], '<', \$p, '>', \my $out, '2>', \my $err;
        if ($out ne "CORRUPTED\n") {
            print "Failed mutating $x to $a\n";
            print "Output: {{{\n$out}}}\n";
            print "Errors: {{{\n$err}}}\n";
            exit;
        }
    }
}

say "All OK!    ";

An n-bit CRC will detect any single error burst not longer than n bits. Hash collisions are impossible in the given case, there's no need for brute-force verification.

@RainerP.: I'm aware that a mutation will prevent the CRC for the portions which originally have a CRC of 0 matching. However, there's the possibility that it could introduce a new substring of the code which has a CRC of 0; the purpose of the brute-forcing is to guarantee that that didn't happen.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
n-th term of the rise & reset sequence
(Challenge taken from a multiplayer game (clash of code) at codingame.com)
The challenge
Find the n-th term of the following sequence: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4... or, to make it more obvious, {1}, {1,2}, {1,2,3}, {1,2,3,4}...
The sequence is made up from concatenated ranges from 1 to x, starting from 1, all the way up to infinity.
Rules / IO
Input and output can be in any format, as long as it's distinguishable. Input can be taken from any appropriate source: STDIN, file, etc...
The input can be 0- or 1-indexed, and the selected indexing must be mentioned in the post.
You will have to handle at least up to a result of 255 inclusive (meaning the 0-indexed maximum input is 32640). Anything over that has to be handled, if your language supports it.
This is code-golf so the shortest byte count wins!
Test cases (0-based indexing)
0 -> 1
1 -> 1
5 -> 3
10 -> 1
59 -> 5
100 -> 10
1001 -> 12

OEIS

You should probably add a few more larger test cases (59, 100, etc)

Related: http://codegolf.stackexchange.com/questions/103670/output-integers-in-negative-order-increase-the-maximum-integer-everytime/

It's the challenge in reverse. The best answers from that challenge work in a way that couldn't be reversed. @JarkoDubbeldam

@devRicher I know, just putting it out there and it wasn't meant negatively. My own answer there actually was reversable. Related != duplicate.

How many terms do we have to support? Is it guaranteed that the input will not overflow our languages' integer types?

@FlipTack Each language has to handle a result at least up to 255 inclusive (meaning the input is higher than 255). Anything over that needs to be handled if your language supports it. I'll edit that in.

What do you mean "the input is higher"? Don't you mean lower or equal to?

@FlipTack No. To arrive at a result of 255, the 0-indexed input has to be 32640.

05AB1E, 5 bytes
The program is 0-indexed, code:
ÌLL¹è

Explanation:
Ì       # Double increment the input
 LL     # List of list on the input
   ¹è   # Get nth element

Uses the CP-1252 encoding. Try it online!

GNG¹¾¼QiN is an iterative approach, but that was smarter.

Haskell, 27 26 bytes
([z|k<-[1..],z<-[1..k]]!!)

Try it online!
Thanks @DanD. for -1 byte!
This is an anonymous function, creating the infinite sequence an just returning the n-th element thereof: [[1..k]| k<-[1..]] produces an infinite list of list: [[1],[1,2],[1,2,3],[1,2,3,4],...]. To concatenate these we can write [z|k<-[1..],z<-[1..k]] which results in [1,1,2,1,2,3,1,2,3,4,...] and finally (...!!) accepts the input n (pointless notation) and returns the n-th term (0-based).

Replacing concat with more comprehension only saves 1 byte: ([z|k<-[1..],z<-[1..k]]!!).

JavaScript, 29 28 bytes
-1 byte thanks to Arnauld!
f=(n,m)=>n++<m?n:f(n+~m,-~m)

Uses the 0-indexed recursive formula found on OEIS.
When called with 1 argument as expected, the default value of the second, m, will be undefined. However, -~undefined, returns 1, which allows us to get the recursion rolling without an explicit m = 1 in the argument list (thanks @Arnauld!)
Test snippet:

f=(n,m)=>n++<m?n:f(n+~m,-~m)

let examples = [0, 1, 5, 10, 15, 1000];

examples.forEach(function log(x) {
    console.log(x, " => ", f(x))
});

Alternatively, for the same byte count, we can have a curried function like so:
f=n=>m=>n++<m?n:f(n+~m)(-~m)

You can call this with f(5)() - it returns a function, which when called, returns the result, as described in this meta post.

Jelly, 5 bytes, 1-indexed
RRF³ị

Try it online!
Explanation:
                                      (Assume N = 4 for the examples)
R      Generate a list of 1 to N      [1, 2, 3, 4]
 R     Generate new lists for each item on the previous list, with that item as N
                                      [[1], [1,2], ...]
  F    Flatten that list              [1, 1, 2, 1, 2, 3 ...]
   ³ị  Use the input number (³) as index (ị) on the list.
       This is one-based:             [1, 1, 2, 1, 2, 3 ...]
                                                ^

Octave, 39 bytes
@(z)z-(n=ceil((8*z+1)^.5/2-.5))*(n-1)/2

1- based index
Explanation:
Consider this sequence:
1   1   2   1   2   3   1   2   3   4   1   2   3   4   5

if we count number of element of subsequences we have
1   2        3          4               5

so using Gauss formula for triangular number
we can form a formula for z:
z=n*(n+1)/2

that is a quadratic equation if we solve it for n we have
n=(sqrt(8*z+1)-1)/2

Try It Online!

Haskell, 25 24 bytes
(!!)$[1..]>>= \x->[1..x]

Usage example: ((!!)$[1..]>>= \x->[1..x]) 10 -> 1. Try it online!.
Maps the anonymous make-a-list-from-1-to-x function \x->[1..x] (the built-in enumFromTo 1 is one byte longer) to the infinite list [1..] and concatenates the resulting lists into a single list. !! picks the nth element.
Thanks to @flawr for one byte.

I think you could shorten it by using (!!)$[1..]>>= \x->[1..x]. Sometimes I really wish there was a shorter pointless way of writing \x->[1..x] :)

PS: Why don't you add a Try it online! link?

@flawr: Well spotted, thanks! Try it online uses an old version of ghc (or  Prelude) and most of answers use <$> which isn't in scope. Do you know any online Haskell compiler/interpreter that uses the newest version? haskell.org only allows expressions and you cannot create links to code you've entered.

Ah, let me tell @Dennis to update it, he is the creator of TIO :)

Octave, 39 bytes
@(n){v=1:n,A=triu(v'+0*v),A(A>0)(n)}{3}

Try it online!
This uses an alternative approach.
For e.g. n=1 this A=triu(v'+0*v) creates the matrix
1   1   1   1
0   2   2   2
0   0   3   3
0   0   0   4

When removing all the zero elements and appending the columns by A(A>0) we get the sequence:
1   1  2  1  2  3  1  2  3  4

Then it is just a matter of exctracting the n-th term of that sequence.

Python, 39 36 bytes
-3 bytes thanks to Dennis!
A recursive lambda which uses 1-based indexing.
f=lambda n,m=1:n*(n<=m)or f(n-m,m+1)

Try it online!
We keep track of the current "rise" size using m. If n is smaller than or equal to m, it fits within the current "rise", and so we return it. However, if it's larger than m, we take m away from it, than add 1 to m and call the function recursively (moving on to the next rise).

R, 25 bytes
i=scan();sequence(1:i)[i]

The index is 1-based.

I saw this bumped to the homepage today, wondered if anyone had submitted a sequence answer, and was happy to see this.

Mathematica, 27 24 bytes
Thanks @MartinEnder for 3 bytes!
((r=Range)@r@#<>1)[[#]]&

1-indexed. This throws errors that are safe to ignore.
Explanation
((r=Range)@r@#<>1)[[#]]&
  r=Range                 (* Store Range function in r *)
           r@#            (* Create list {1..n} *)
 (r      )@               (* For each element, generate {1..n} *)
              <>1         (* Join the lists and append a 1; throws errors *)
(                )[[#]]&  (* Take the nth element *)

Join@@ is way too expensive ;) ((r=Range)@r@#<>1)[[#]]&

@MartinEnder Woah, abusing the fact that StringJoin is not evaluated... I like it

Pyth, 6 5 bytes
1 byte saved thanks to @TheBikingviking!
@s._S

This uses 0-based indexing.
Try it online!
Explanation
@          Index with implicit input into
   ._      all prefixes of
     S     1-based range of implicit input
 s         concatenated into an un-nested list

Nice! You can replace .n with s.

@TheBikingViking Thanks!

brainf*ck, 78 bytes
,>+<[>[->>+>+<<<]>>>[-<<<+>>>]<<+[->->+<<]>[<<->>>[-<<+>>]<[-]]>[-]<<<+<-]>>+.

Takes input (0-based) and outputs as byte values.
You can test it here.
Input requires a \ before decimal numbers (e.g. \10 for 10). If the output is a printable ASCII character, you should see it. Otherwise, hit view memory -> final dump. The value that was printed is in the 3rd cell (cell number 2).
Explanation:
Cell 0 (INPUT): is the input and is decremented my 1 each time through the loop.
Cell 1 (RESET): increments by 1 every time it is equal to TERM. To do this, every time through the loop we add 1 and if they are not equal we subtract 1.
Cell 2 (TERM): increments by 1 every loop and is set to 0 if it matches RESET. To do this, I only copy the value back from HOLD if this cell was not equal to RESET.
Cell 3 (EQUAL): is used to check if RESET and TERM are equal.
Cell 4 (HOLD): is used to copy the values of RESET and TERM back after the equals check.
,>+<              # get input and put a 1 in RESET
[                 # for INPUT to 0
  >[->>+>+<<<]    # copy RESET to EQUAL and HOLD
  >>>[-<<<+>>>]   # copy HOLD back into RESET
  <<+             # add 1 to TERM
  [->->+<<]       # subtract TERM from EQUAL and copy it to HOLD
  >[              # if RESET and TERM were not equal
    <<-           # subtract 1 from RESET
    >>>[-<<+>>]   # copy HOLD back to TERM
    <[-]          # zero out EQUAL
  ]               # end if
  >[-]            # zero out HOLD
  <<<+            # add 1 to RESET (this cancels out the subtraction if
                  #     RESET did not equal TERM)
  <-              # subtract 1 from INPUT
]>>+.             # end for and add 1 because the sequence resets to 1 not 0

Good job! I'll test this and award the bounty right after. Mind adding an explanation? :)

@TuukkaX I was working on that :) I'll try to add some more when I have time tonight.

Seems to work :) Bounty available in 20 hours.

@TuukkaX Keep in mind that the bounty should be left available for all 7 days to draw attention, then awarded on the last day.

@mbomb007 Hmm. I announced that I'll award the bounty to the first to submit a brainf*ck solution, which means the competition for the bounty is over. However, other people are doing the same you mentioned, and it's a good way to compensate for the points that I lost. Thanks :)

I started thinking of a BF solution as soon as I saw the bounty, but this answer already existed then. Still, it only took me an hour to make my solution.

@mbomb007 I think a happened to see the bounty within a few minutes of it being posted. I guess I got lucky.

The interpreter you're using is kind of limited. I'd recommend looking at the one I used.

@mbomb007 Thanks! I was just using the first one I found. Is there a good way to see the byte value of what was printed?

I kind of explain it in my BF answer. Print in a # after every . to get a memory dump for that time. Then look for the cell that is bold, which will be the value where the pointer is, and the value that was printed. You have to turn on the memory dumps option for this to work.

Perl 6, 21 bytes
{map(|^*,^∞)[$_]+1}

0-indexed. Try it online!
How it works:
{                 }  # A lambda.
         ^∞          # Range from 0 to Inf-1. (Same byte count as 0..*, but cooler.)
 map( ^*,  )         # Map each number n to the range 0..(n-1),
     |               # And slip each range into the outer list.
            [$_]     # Index the sequence with the lambda argument.
                +1   # Add 1.

Perl 6, 21 bytes
{[\,](1..*).flat[$_]}

0-indexed. Try it online!
How it works:
{                   }  # A lambda.
      1..*             # Range from 1 to infinity.
 [ ,](    )            # Fold it with the comma operator,
  \                    # and return all intermediate results, e.g. (1), (1,2), (1,2,3)...
           .flat       # Flatten the sequence.
                [$_]   # Index it with the lambda argument.

Pyke, 6 bytes
OmSsQ@

Try it here!
O      -    input+2
 mS    -   map(range(1,i+1), range(^))
   s   -  sum(^)
    Q@ - ^[input]

0-indexed.

R, 43 41 bytes
Edit: Found a shorter recursive approach by using A002262 + 1 (0 indexed):
f=function(n,m=1)`if`(n<m,n+1,f(n-m,m+1))

Old version:
n=scan();n-choose(floor((1+sqrt(8*n))/2),2)

1-indexed formula from OEIS.

Try It Online! It seems to work just fine. :)

I managed to save a few bytes compared to your solution. See my answer.

MATL, 8 bytes
:"@:]vG)

This solution uses 1-based indexing
Try it at MATL Online
Explanation
        Implicitly grab input (N)
:       Create an array from [1...N]
"       For each element (A) in this array...
  @:    Create an array from [1....A]
]       End for loop
v       Vertically concatenate everything on the stack
G       Explicitly grab the input again
)       And use it to index into the vertically concatenated array
        Implicitly display the result

Not that it matters a lot, but the code is much faster if you move v after ]

@LuisMendo Ah good point! I like short and fast!

But that's a short-circuited and, of course! :-)

Brain-Flak, 46 bytes
Zero indexed
(<>()){(({}())[()]){({}[()])<>}{}}<>([{}()]{})

Try it online!
Stack Clean, 48 bytes
(<>()){(({}())[()]){({}[()])<>}{}}{}<>([{}()]{})

Try it online!
Explanation
This is a modified version of the modulo function. Instead of using a constant number as the divisor it increments the divisor for each time the divisor is subtracted from it (once per outside loop iteration).
Annotated Code
(<>())       # Switch to the opposite stack and push 1 (the initial divisor)
{            # (outside loop) While top of stack is not 0...
  (          # Push...
    ({}())   # Push the divisor plus 1
  [()])      # ...minus one (ie push a copy of the original divisor
  {          # (inner loop) While the top of stack does not equal zero
    ({}[()]) # Decrement the top of the active stack
    <>       # Switch stacks
  }{}        # (inside loop) End loop and pop zero off the top of stack)
}            # (outside loop) End loop
<>           # Switch stacks (to the one with the divisor)
([{}()]{})   # Calculate the result

Neither of these solutions is as short as JungHawn Min's, but they're alternate approaches, which is something I guess. Both are unnamed functions taking a (1-indexed) positive integer input and returning a positive integer.
Mathematica, 30 bytes
-#^2-#&@⌈√(2#)-3/2⌉/2+#&

An actual mathematical formula for this function! Made more readable (in part by translating the 3-byte characters ⌈, √, and ⌉):
# - ((#^2 + #) / 2 &)[Ceiling[Sqrt[2 * #] - 3/2]] &

Ceiling[Sqrt[2 * #] - 1/2] tells us which sublist the input refers to, from which we subtract one to tell us which sublist ends before we get to the input; then ((#^2 + #) / 2 &) computes how many elements occur in all the sublists before the one we care about, which we subtract from the input # to get our answer. (Some will notice the familiar formula (#^2 + #) / 2 for the #th triangular number; Ceiling[Sqrt[2 * #] - 1/2] is essentially the inverse function.)
Mathematica, 32 bytes
If[#2<=#,#2,#0[#+1,#2-#]]&[1,#]&

Recursive solution, basically the same as in Billywob's answer and others.

Java 8, 85 73 55 bytes
n->f(n,1)+1int f(int n,int m){return n<m?n:f(n-m,m+1);}

0-indexed recursive approach with the formula provided in the OEIS:

a(n) = 1 + A002262(n).
A002262: a(n)=f(n,1) with f(n,m) = if n<m then n else f(n-m,m+1).

Try it here.

Old answer (85 56 bytes):
n->{int m=~-(int)Math.sqrt(8*n+1)/2;return n-m*-~m/2+1;}

Used the other 0-indexed formula provided in the OEIS:

n-th term is n - m*(m+1)/2 + 1, where m = floor((sqrt(8*n+1) - 1) / 2).

Try it here.

QBIC, 21 bytes, 1-indexed
:[a|[b|~q=a|_Xc\q=q+1

Explanation:
:      Get 'a' from the cmd line
[a|    FOR (b = 1; b <= a; b++) This creates an outer loop from 1 to N
[b|    FOR (c = 1; c <= b; c++) This creates an iteration, yielding the 1, 12, 123 pattern
       'q' stores how many terms we've seen. It starts at 1 b default.
~q=a   if we are at the desired term (q == a)
|_Xc   Then quit, and print 'c' (the current number in the sequence)
\q=q+1 Else, increase 'q' and run again.

Slightly more interesting approach, but 10 bytes longer:
:{~b+q>=a|_xa-b|\b=b+q┘q=q+1

This program continuously calculates the total number of numbers in this bracket and all previous ones (1 at loop 1, 3 at loop 2, 6 at loop 3 ...). When that counter exceeds the sought-after index N, then return X from the current bracket, where X is N minus the previous amount of the counter.

Perl, 30 bytes
29 bytes of code + -p flag.
map{$\-=$c++if$c<++$\}0..$_}{

Try it online!

C, 81 44 bytes
straight iterative method, 0 indexed, and with some gentle massaging;
m=1,c=1;f(n){for(;n--;c=c^m?c+1:!!++m);c=c;}

Try it online!

Try It Online! It works. :)

dc, 21 bytes, 0-based indexing
?d8*1+v1-2/d1+*2/-1+p

Try the dc program online!
Explanation:
?      Push input number n.
d      Duplicate n at the top of the stack.
8*1+   Replace n at the top of the stack with 8n+1.
v      Replace 8n+1 at the top of the stack with the floor of its square root.
1-2/   Subtract 1, and divide by 2 (ignoring any fractional part).

The top of the stack now holds the index k of the greatest triangular number that is <= n.
d1+*2/ Compute k(k+1)/2, which is the greatest triangular number <= n.
-      Subtract n-(the greatest triangular number <= n). The first n is on the stack in position 2, because the input number n was duplicated at the top of the stack at the very beginning of the program, and only one of the values was popped and used (until now).
1+     Add 1 because the desired sequence starts over again at 1 (not 0) at every triangular number.
p      Print the answer.

This dc program can be converted into a competitively-sized bash script:
Bash + Unix utilities, 28 bytes, 0-based indexing
dc -e"?d8*1+v1-2/d1+*2/-1+p"

Try the bash program online!

Ruby, 30 bytes
->n{(0..n).find{|x|0>=n-=x}+n}

1-based indexing

R, 37 bytes
n=scan();for(i in 2:n)T=c(T,1:i);T[n]

Takes input from n, and creates the sequence for the first n sequences. This makes it somewhat inefficient at higher inputs, but it should be fine. It then returns the n-th entry, 1-indexed.
Uses a nice little trick by starting off the sequence with T, which is TRUE or 1 by default.

C11, 48 bytes
int f(int x){int q=1;while(x>q)x-=q++;return x;}

Try it online!
Also works in C++ and Java.

An alternative for the same byte count:
int f(int x){int q=0;while(x>++q)x-=q;return x;}

Umm.. Neither seems to work for most of the test cases.. Try it here

brainfuck, 141 bytes
I know I'm too late for the bounty, but I just wanted to see how many bytes the algorithm I thought of would end up being.
This program is zero-indexed.
,>+<[[->>+>+<<<]>>[-<<+>>]<[->+>>+<<<]>[-<+>]>>+[[-<->>+<]>[-<+>]<<<<]>>[>>>]>[.[<<<]]<<<<<<<[[-]>>>[-<+<<+>>>]<[->+<]<<<<<]>>>[>>>]<<<]>[.>]

Try it online

Select Dynamic (infinite) Memory, or it won't work
To test input values > 255, change Cell size (Bits) to 16 or 32.
The interpreter explains how to give input. For decimal input use \5 for input of 5.

The maximum decimal value you can test input with is \999
Hex input can go as high the cell-size.

Explanation:
This shows the program broken up by step, showing what happens for input of 5. # are placed in the ideal memory dump locations for the interpreter.
You will probably want to use checkbox Dump Memory at char: # if running this version. This will dump the memory upon hitting #, allowing you to see the value on the tape in the event that it's an unprintable character, or to see what happens at any step you want. The cell that the pointer is on will be in bold.
,>+<                       (5) 1
[[->>+>+<<<]>>[-<<+>>]       5 1 (0) 5
<[->+>>+<<<]>[-<+>]>>+       5 1 0 5 (2)
[[-<->>+<]>[-<+>]<<<<] (0) 0 4 1 0 3 2 0 0
>>[>>>]                      4 1 0 3 2 0 (0) 0
                             1 1 0 (0) 2 0
>[.#[<<<]]<<<<                4 1 0 (3) 2 0 0 0
<<<[[-]>>>[-<+<<+>>>]<[->+<]<<<<<]>>> (3) 1 0 3 2 0 0 0
[>>>]<<<]>[.#>]

Tape structure:
    (cell_1 cell_2 temp), (cell_1 cell_2 temp), ...

Take Input;
If not zero:
  copy last pair to the right and add one to its cell_2
  subtract each cell_2 from each cell_1 (leaving each cell_2 intact)
  move checking from left to right:
    If cell_1 is zero and cell_2 isn't:
      print cell_2
    Else:
      copy last cell_1 back, overwriting each previous cell_1
Else:
  right one and print result

Try it online

Select Dynamic (infinite) Memory, or it won't work
Dump Memory at char: #

Notes:

To run this on another interpreter that doesn't allow moving to the left of the starting cell (that's why I use Dynamic Memory), put in a bunch of > at the start. The number required may vary depending on the input value, but is O(1).

tinylisp (repl), 90 bytes (0-indexed)
(d r(q((n j x)(i n(i(e j x)(r(s n 1)1(s x(s 0 1)))(r(s n 1)(s j(s 0 1))x))j
(q((n)(r n 1 1

Or, non-competing (using a feature that was committed after this challenge was posted), 80 bytes:
(d r(q((n j x)(i n(i(e j x)(r(s n 1)1(a x 1))(r(s n 1)(a j 1)x))j
(q((n)(r n 1 1

The first line defines a helper function r, and the second line is an unnamed function that takes n and returns the nth term of the sequence. I've specified this as a repl submission because the repl autocompletes parentheses at the end of every line, not just at the end of the program. With those caveats, here's a version modified to work at Try it online, and here's an ungolfed version run against inputs 0 through 54.
Explanation
I'll use the noncompeting version here. The only difference is that the official version has to implement addition as two subtractions.
(d r           Define r to be:
 (q(           A lambda function (= a list of two elements, quoted to prevent evaluation):
  (n j x)       Arguments n, j (the range counter), and x (the range limit)
  (i n          If n is truthy, i.e. nonzero:
   (i(e j x)     If counter equals limit:
    (r            Call r recursively on:
     (s n 1)       n-1
     1             counter reset to 1
     (a x 1))      limit increased by 1
    (r           Else, call r recursively on:
     (s n 1)       n-1
     (a j 1)       counter increased by 1
     x))           same limit
   j))))        Else, we're done; return the counter value

(q(            Lambda function:
 (n)            Argument n
 (r n 1 1)))    Call r with n, counter = 1, range limit = 1

C, 54 bytes
Not the shortest C solution, but it has the merit of running in constant time (no loops, just math). It uses zero-based indexing:
x;f(n){x=floor(sqrt(8*n+1)-1)/2;return 1+n-x*(x+1)/2;}

Ungolfed:
int f(int n) {
    int x = floor(sqrt(8*n+1)-1)/2; //calculate the number of the current subsequence (zero based)
    return 1+n-x*(x+1)/2;   //x*(x+1)/2 is the zero based index of the `1` starting the subsequence
}

Test with:
#include <math.h>
#include <assert.h>
#include <stdio.h>

x;f(n){x=floor(sqrt(8*n+1)-1)/2;return 1+n-x*(x+1)/2;}

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

    assert(f(0) == 1);
    assert(f(1) == 1);
    assert(f(5) == 3);
    assert(f(10) == 1);
    assert(f(59) == 5);
    assert(f(100) == 10);
    assert(f(1001) == 12);
}

C, 103 bytes
For a begginer it's okay, I think :).
int main(){int n,c,i,j;scanf("%d",&n);while(c<n){for(i=1;i<=j;i++){c++;if(c==n)printf("%d",i);}j++;}}

or the formatted way
#include <stdio.h>

int main() {
    int n,c,i,j;
    scanf("%d",&n);
    while(c<n)
    {
        for(i=1;i<=j;i++)
        {
            c++;
            if(c==n) printf("%d",i);
        }
        j++;
    }
}

If you declare n,c,i,j as globals, it is guaranteed they are initialized to 0, which is not true of locals.

I knew it'd contain such unexperienced mistakes.
n is the input or the n-th number in the sequence, c is a counter, i and j are loop elements; j will be 1 then 2 then 3 while i will be 1 then 1,2 then 1,2,3 and so on. @Qwerp-Derp

I'm not sure if I understood exactly what you mean but the initial values will be 0 in this code whether I declared them as globals or locals. Please correct me ıf I'm wrong 0=). @feersum

No, uninitialized local variables aren't set to 0. http://stackoverflow.com/questions/15268799/uninitialized-variable-in-c

Pushy, 11 bytes
1-indexed implementation.
R&:{R;&:{;#

Try it online!

Thunno 2, 5 bytes
ƙRRḞi

Try it online!
Port of Adnan's 05AB1E answer.
Explanation
ƙRRḞi  # Implicit input
ƙ      # Increment it twice
 RR    # Double range
   Ḟi  # Flatten and index in
       # Implicit output

J-uby, 22 bytes
~:[]%(:+|:flat_map+:+)

Attempt This Online!

APL, 9 bytes
{⍵⊃∊⍳¨⍳⍵}

Explanation:
⍵⊃           ⍝ ⍵'th element of
  ∊          ⍝ concatenated elements of
   ⍳         ⍝ each list from 1 to N
    ¨        ⍝ for each N in
     ⍳⍵      ⍝ list from 1 to ⍵

Batch, 55 bytes
@set/am=%2+1,n=%1-m
@if %n% gtr 0 %0 %n% %m%
@echo %1

1-indexed. Like some of the other recursive answers, this keeps track of which range it's in using a second argument that defaults to the empty string. This means that m equals 1 on the first pass. The loop ends when n falls below 1 in which case the previous value of n is the answer.

PHP, 41 bytes
seems like there´s nothing shorter in PHP. Damn the dollars.
for($s=$argv[1];$s>0;$s-=++$i);echo$i+$s;

1-indexed. Run with -r or Try it Online.

Try It Online! In Bash, as it was more convenient and I could not figure out how to use flags on the actual PHP page, but at least it proves that the code works. :)

@R.Kap  The actual PHP page needs no flags. -r tells PHP to run code from the command line instead of from a file. But thanks for the TiO.

Scala, 45 bytes
(n:Int)=>Stream.from(1)flatMap(1 to _)apply n

0-indexed.

dc, 47 bytes, 0 indexed
?0sb1se[0sble1+se]sf[lb1+dsble=f1-d0!>c]dscxlbp

Try It Online!
Explanation
This explanation assumes that the input is 100.
?                                               # Ask for inout and store it on top of the main stack.
                                                # Main = [100].
 0sb1se                                         # Store 0 on top of register "b" and 1 on top of register "e" to be referenced later.
                                                # b = [0], e = [1], Main = [100].
       [0sble1+se]sf                            # Store the macro "0sble1+se" on top of register "f".
                                                # f = [0sble1+se], b = [0], e = [1], Main = [100].
                    [lb1+dsble=f1-d0!>c]dscx    # Store the macro "lb1+dsble=f1-d0!>c" on top of Main stack, duplicate it, and then store one copy on top of register "c" and then immediately executing the other copy as a dc program.
                                                # c = [lb1+dsble=f1-d0!>c], f = [0sble1+se], b = [0], e = [1], Main = [100]

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

Upon invocation of the macro `lb1+dsble=f1-d0!>c`:

    lb1+dsble            # Load (not pop) the value off of the top of register "b" on top of the main stack, add 1 to it, duplicate the sum, and then push one copy to the top of register "b".
                         # Then, load the value off of the top of "e" onto the main stack.
                         # b = [0,1], e = [1], Main = [100,1,1].
             le=f        # Now, pop the top 2 values (1 and 1), compare them, and invoke the macro on top of register "f" if both are equal. In this case, it is invoked, since 1==1.
                         # b = [0,1], e = [1], Main = [100].

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

     If the macro on top of "f" (`0sble1+se`) is invoked:

         0sble1+se # Push 0 to the top of the Main stack. Then, push it to the top of register "b", resetting the sequence, after which the value on top of "e" is loaded onto the main stack.
                   # Then, this value is incremented by 1. This new value os finally pushed to the top of register "e".
                   # b = [0,1,0], e = [1, 2], Main = [100]

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

                 1-d0!>c # Finally, decrement the value on top of the Main stack (the input) by 1, duplicate this, pop and compare this value with 0, and as long as the `input-1`>=0, keep on executing this macro.
                         # b = [0,1,0], e = [1, 2], Main = [100,99]

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

                                            lbp # Finally, once all the iterations of the macros have taken place, load the n'th value of the sequence off of the top of register "b", and then output it.
                                                # At the end, b = [0,1,0,1,2,0,1,2,3,0,1,2,3,4,...] and Main=[100,99,...,0,-1].

Bash + BSD utilities (MacOS X, etc.), 28 bytes, 1-based indexing
jot -wjot\ %d $1|sh|sed $1!d

Bash + standard utilities (GNU or BSD), 29 bytes, 1-based indexing
seq $1|xargs -n1 seq|sed $1!d

Try the GNU version online!
BSD's jot is a little golfier than the GNU seq utility, since jot lets you use the %d printing code, whereas seq requires %.f (which is one byte longer) to get a similar effect.

QBasic, 43 bytes
INPUT a
i=1
WHILE a-i>0
a=a-i:i=i+1
WEND
?a

1-based. Try it online!

Pyt, 16 bytes
←Đř△⇹Đ↔Đ04Ș<*↑+-

Solution is 1-indexed
Explanation:
Code                               Explanation (with stack in parentheses) (sample input of 5)
←                              Get input (5)
 Đ                             Duplicate input (5,5)
  ř                            Push [1,2,...,top of stack] (5,[1,2,3,4,5])
   △                           Triangle numbers (5,[1,3,6,10,15])
    ⇹                          Swap top two elements ([1,3,6,10,15],5)
     Đ                         Duplicate top ([1,3,6,10,15],5,5)
      ↔                        Flip stack (5,5,[1,3,6,10,15])
       Đ                       Duplicate top (5,5,[1,3,6,10,15],[1,3,6,10,15])
        0                      Push 0 [this is to allow the next step] (5,5,[1,3,6,10,15],[1,3,6,10,15],0)
         4Ș                    Flip top four elements (5,0,[1,3,6,10,15],[1,3,6,10,15],5)
           <                   Less than (5,0,[1,3,6,10,15],[True,True,False,False,False])
            *                  Multiply (5,0,[1,3,0,0,0])
             ↑                 Get maximum (5,0,3)
              +                Add [this is to get rid of the 0 inserted earlier] (5,3)
               -               Subtract (2)

Husk, 4 bytes
!ΣḣN

This uses 1-indexing, try it online! (Or try this which uses 0-indexing)
Explanation
!ΣḣN  -- takes an integer N as argument, for example 5
   N  -- natural numbers: [1,2,3,4,…
  ḣ   -- rangify each: [[1],[1,2],[1,2,3],[1,2,3,4],…
 Σ    -- concatenate: [1,1,2,1,2,3,1,2,3,4,…
!     -- index into that list: 2

Python 2, 50 bytes
Try it online!
c=1
u=0
n=input()
while u<n:u+=c;c+=1
print(n-u+c)

I have a feeling this can be golfed a lot, but this is what I have so far.

49 bytes

Haskell, 23 bytes
(!!)$do x<-[1..];[1..x]

Try it online!
Alternatively, (do{x<-[1..];[1..x]}!!) has the same length.

Japt, 6 bytes
With 0-based indexing.
gUõ cõ

Try it (includes all test cases)
gUõ cõ     :Implicit input of integer U
g          :Index into
 Uõ        :  Range [1,U]
    c      :  Flat map each X
     õ     :    Range [1,X]

Vyxal, 32 bitsv2, 4 bytes
Þ∞ɾfi

Try it Online!
Explained
Þ∞ɾfi
Þ∞     # All the natural numbers (like actually all of them)
  ɾ    # rangified (1..n) (possible because lazy)
   f   # flattened (also possible because lazy)
    i  # get the inputh item

Created with the help of Luminespire.


text:
A prime test that's LITERALLY prime
Write a program that will test the primality of a specified number, and give the output as a Boolean value (True is prime). Your prime test can (but doesn't have to) be valid for the number 1.
Here's the catch: your program itself has to sum to a prime number. Convert every character (including spaces) to its Unicode/ASCII value (table). Then, add all those numbers together to get the sum of your program.
For example, take this not-so-great program I wrote in Python 3.3:
q=None
y=int(input())
for x in range(2,int(y**0.5)+1):
    if y%x==0:
        q=False
if not q:
    q=True
print(q)

If you convert all the characters to their corresponding Unicode/ASCII value, you get:
113 61 78 111 110 101 10 121 61 105 110 116 40 105 110 112 117 116 40 41 41 10 102 111 114 32 120 32 105 110 32 114 97 110 103 101 40 50 44 105 110 116 40 121 42 42 48 46 53 41 43 49 41 58 10 32 32 32 32 105 102 32 121 37 120 61 61 48 58 10 32 32 32 32 32 32 32 32 113 61 70 97 108 115 101 10 105 102 32 110 111 116 32 113 58 10 32 32 32 32 113 61 84 114 117 101 10 112 114 105 110 116 40 113 41

You can then find the sum of those numbers manually or with your own program. This specific program sums to 8293, which is a prime number.
Of course, this is Code Golf, so the smaller you can make your program, the better. As pointed out by other users, this program is not very golfy.
A few rules:
Valid inputs include STDIN and prompts (no functions, it's just a way to  add free extra code). Spaces are permitted, but only if they are crucial to the functionality of your program. Output must be an output, not just stored in a variable or returned (use print, STDOUT, etc.)
Flags can be used and should be counted literally, not expanded. Comments are not allowed. As for non-ASCII characters, they should be assigned to the value in their respective encoding.
Make sure to list your program's size and the sum of the program. I will test to make sure programs are valid.
Good luck!
Here is a snippet to count the sum of your program and check if it is prime:

function isPrime(number) { var start = 2; while (start <= Math.sqrt(number)) { if (number % start++ < 1) return false; } return number > 1; } var inp = document.getElementById('number'); var text = document.getElementById('input'); var out = document.getElementById('output'); function onInpChange() { var msg; var val = +inp.value; if (isNaN(val)) { msg = inp.value.toSource().slice(12, -2) + ' is not a valid number.'; } else if (isPrime(val)) { msg = val + ' is a prime number!'; } else { msg = val + ' is not a prime number.'; } out.innerText = msg; } function onTextChange() { var val = text.value; var total = new Array(val.length).fill().map(function(_, i) { return val.charCodeAt(i); }).reduce(function(a, b) { return a + b; }, 0); inp.value = '' + total; onInpChange(); } text.onkeydown = text.onkeyup = onTextChange; inp.onkeydown = inp.onkeyup = onInpChange;
body { background: #fffddb; } textarea, input, div { border: 5px solid white; -webkit-box-shadow: inset 0 0 8px  rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1); -moz-box-shadow:  inset 0 0 8px  rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1); box-shadow:  inset 0 0 8px  rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1);  padding: 15px; background: rgba(255,255,255,0.5); margin: 0 0 10px 0; font-family: 'Roboto Mono', monospace; font-size: 0.9em; width: 75%; }</style><meta charset="utf-8">


text:
Hello World!... in pure x86 opcodes
This is a Hello World challenge! Those plain ones! Yeah....
However, it's different this time.
Because here, you can't use C or C++ or Stuck or ArnoldC or whatever you want. You can only choose raw x86 opcodes from this list, or any other x86 opcode lists.
It is also assuming you have no Protected Mode or any other thing, and you are in 16bit or 32bit Real Mode with nothin' loaded for ya'.
To represent a register, you can use something like [ECX] or [AL].
If you have to halt or for some reason display a trailing newline (i thought that would only happen in high-level languages!), do it.
Every byte or register is represented as one byte instead of 2.
This is a code-golf question. Whoever can do it with the least bytes wins. This is not a duplicate, and you can't use Linux (int 0x80) or DOS (int 0x21). You can't use ELF/i686 code either. It has to be plain raw machine code.
Have fun!
An example that prints 'A' in 16bit real mode and advances the cursor in 10 bytes (if you want Hello World, you will have to repeat this a million times, and each time changing the letter, which is in AL, and this is not an answer):
B0 [AH] [AH] 0E B0 [AL] [AL] 41 CD 10

This has no objective winning criteria. All programming contests here need one to decide who the winner is. It seems like you wanted [tag:code-golf] here. (I only noticed because my dupe hammer didn't work :))

Assuming this is code golf, this is just a language-specific version of our general Hello, World! challenge. Any answer to this could simply be posted there instead. There's an x86 answer and an x86_64 answer as well. If you think these aren't satisfactory, you could always earn some reputation and then offer a bounty to encourage better answers in your language of interest.

Both x86 answers to the general question are OS specific. The challenge here is to write a program which relies only on the BIOS functions like INT 10h (a boot loader displaying "Hello world" without using any OS function). Not really code golf, hardly a programming puzzle, but I wouldn't call it a duplicate.

@GB Nevertheless, that's a valid language choice for the general challenge.

You have to only use those opcodes (also known as machine code) to make "Hello World!" as code-golf. Forgot to add that tag, sorry.

Asserting "this is not a duplicate" doesn't make it true. By the standards of this site, it is a duplicate: any valid competitive answer to this question would be a valid competitive answer to the indicated question.